Search code examples
javalistobjectreturn-typeobject-type

How can I make a java method return an object found in a list of objects?


I have this code:

    public Task getTask(String taskID) {
        
        for (Task item : tasks) {
            if (item.getTaskID() == taskID) {
                return item;
            }
        }
    }

Task is an object type, and "tasks" is a list containting all objects of type Task.

I want to iterate through the list and find the object where the taskID matches. This seems to work, but when I try to test or run, Eclipse tells me that this method "must return an a result of type Task".

I'm not sure what I have wrong. If each "item" is an item in the list, shouldn't it be of type Task?

I've tried iterating through the list by index numbers as well and that doesn't seem to work either.


Solution

  • Instead of using '==' to compare strings, you can use the equals() method. This is because '==' compares object references, not the contents of the strings themselves.

    public Task getTask(String taskID) {
        for (Task item : tasks) {
            if (item.getTaskID().equals(taskID)) {
                return item;
            }
        }
        return null;
    }