How to return an object inside an array?



I have an assignment for uni and I’m stuck with a question for quite some time.

So, I have to return an object which is called Fruit in the method first (which is the method where I need help with).

(Fruit is defined in another class like this : Fruit(String name, String nickname, int taste).)

The method first is meant to return the fruit with the best taste.

But I keep having the NullPointerException for either taste or fruit. I do understand what the error means but I don’t have any idea about how to correct it. Thanks for those who can help! And sorry about the bad English.

public class Four {
    private Fruit[] fruits;
    Four(Fruit f1, Fruit f2, Fruit f3, Fruit f4) {
        Fruit[] m = new Fruit[4];
        m[0] = f1;
        m[1] = f2;
        m[2] = f3;
        m[3] = f4;
    }

    public Fruit[] getFruit() {
        return fruits;
    }

    public Fruit first() { //THIS FIRST LINE CAN'T CHANGE
        Fruit[] e = new Fruit[4];
        Fruit f = e[0];
        for (int i = 1; i < 3; i++) {
            if (f.taste > e[i].taste) {
                f = e[i];
            }
        }
        return f;
    }

    public static void main(String[] args) {
        Fruit f1 = new Fruit("Apple", "Appie", 5);
        Fruit f2 = new Fruit("Strawberry", "Strawy", 20);
        Fruit f3 = new Fruit("Banana", "Banie", 18);
        Fruit f4 = new Fruit("Orange", "Orangi", 8);
        Four m = new Four(f1, f2, f3, f4);
        System.out.println(m.first());
    }
}

Answer

In the code

Fruit [] e = new Fruit[4];
Fruit f = e[0];

The accessed array index e[0] has a null value. So f.taste > e[i].taste will throw NPE. (any e[i]. will throw NPE)

Suggested changes

Constructor

Fruit [] m = new Fruit[4];.

This has to be changed to fruits = new Fruit[4]; (and all assignments to m[] should be made to fruits[]

This will help these constructed values to be accessible to other parts of same object.

Otherwise, the fruits instance variable will be null and will not track the state of the object.

first method

Fruit [] e = new Fruit[4];

After making the necessary changes to constructor, the above line can be changed to Fruit [] e = this.fruits;(or directly access fruits[] instead of assigning to e).

This will ensure the expected object state is being used in the first method.



Source: stackoverflow