My List in Java is coming out null, instantiating it doesn't seem to work... help?
Searched around the site and google nothing seems to come in for what I'm sure is a super simple problem.
So I have a list I declare like so:
private List<Integer> mList;
When I try to do a method on it like mList.add(...);
it doesn't work, returns a null pointer exception. I tried to instantiate the List like so:
public Class() {
mList = new List<Integer>();
But this is also incorrect, at least according to my IDE Eclipse. I can't seem to word the开发者_运维百科 problem right when I search around because as simple as this is, nothing really shows what I want to do without making it an ArrayList or something else I'm not trying to do. Thanks for bearing with this simple question.
A variable must be initialized before it can be used. Otherwise it is null and you get NullPointerExceptions.
Java has interfaces, which are like classes with only methods defined. However you cannot create real objects from them. They just serve to define the contract.
java.util.List is such an interface.
You have to use a real class which implements that interface
e.g.
private List<Integer> mList = new ArrayList<Integer>();
java.util.ArrayList is an implementation of List, and this will do as you expect.
You should declare and instantiate it. Also, list is an interface, so you cannot instantiate it with a list. Instead, instantiate it with a class that implements list. For example:
private List<Integer> mList = new ArrayList<Integer>();
List
is an interface and cannot be instantiated using new
directly. Use one of its implementations such as ArrayList
or LinkedList
.
mList = new ArrayList<Integer>();
You cannot instantiate a type of List
since it is an interface. Pick an implementation of List
, such as ArrayList
, like the following code:
List<Integer> mList = new ArrayList<Integer>();
精彩评论