Dexter
Dexter

Reputation: 197

Why we can use methods of ArrayList without creating new ArrayList object?

We have to create a object of any class to use their funtionalities unless those are static functionalities. But why we dont need to create a ArrayList object to use its methods like add, contains etc..

ArrayList<Egg> myList = new ArrayList<Egg>();
myList.add(a);

According to my understanding, myList is just variable which holds ArrayList object's reference of type ArrayList class. So again how can we write following without passing object to myList.

ArrayList<Egg> myList;
myList.add(a);

Complete code:

import java.util.ArrayList;

public class DotCom {
    private ArrayList<String> locationCells;

    public void setLocationCells(ArrayList<String> loc)
    {
        locationCells = loc;
    }

    public String checkYourself(String userInput)
    {
        String result = "miss";
        int index = locationCells.indexOf(userInput);
        if (index >= 0) {
            locationCells.remove(index);
            if (locationCells.isEmpty()) {
                result = "kill";
            }
            else
            {
                result = "hit";
            }
        }
        return result;
    }

    //TODO:  all the following code was added and should have been included in the book
    private String name;
    public void setName(String string) {
        name = string;
    }
}

PS I am referring heads first java book.

Upvotes: 0

Views: 1396

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

The ArrayList reference is being set in the setter method:

public void setLocationCells(ArrayList<String> loc)
{
    locationCells = loc;
}

If this method is not called, and the reference not set before trying to use the ArrayList, then the code will throw a NullPointerException.

Side note: This does not look to be safe code, since it can be easily run incorrectly and so a NPE is easy to create. Better perhaps to set the ArrayList (List is even better) in a constructor.

Upvotes: 1

Related Questions