#getItem function

1 messages · Page 1 of 1 (latest)

hushed elbow
#

Hi im just learning java and don't know what would be the best way to create this type of function, i know syntax is incorrect. Maybe someone can suggest me something

    public Item getItem(int id, int position) {
        if (id != null) {
            for (Item x : items) {
                if (x.getId() == id) {
                    return x;
                }
            }
        } else {
            for (int i = 0; i< items.size(); i++) {
                return items.get()
            }
        }
    }
tiny sandalBOT
#

<@&987246399047479336> please have a look, thanks.

hexed ridge
#
public Item getItem(Integer id, int position) {
    if (id != null) {
        for (Item x : items) {
            if (x.getId() == id) {
                return x;
            }
        }
    } else {
        if (position >= 0 && position < items.size()) {
            return items.get(position);
        }
    }
    return null;
}```
tiny sandalBOT
prisma dune
#

yeah - the important distinction here between int and Integer is that Integer can be null

#

so if you want to sometimes pass null, Integer

humble palm
#

You could also use an invalid value in the place of null if you want to be careful about exceptions, like a negative number

#

As another alternative, you can overload the function.

#

It's not useful in this case but in a more complex example, it might be.

prisma dune
#

well actually

#

i would do

#
public Item getById(int id) {}
public Item getByPosition(int position) {}
hushed elbow
#

Thanks