0

i am using a List of <Friend>, Friend is a class that i have with some info about a person, name, desc, etc...

ok, this is the code on the start of the class:

private List<Friend> friends;

and later... in a method of the class:

Friend a = new Friend("Pablo SáeZ", "Total", "39.68333", "-0.32667", new Date());
friends.add(a);

ok, i have the nullpointerexception on the line friends.add(a);

can someone explain why?

thanks

1
  • I've rollbacked your edit. Please press Ask Question button if you have a new question. Don't edit an exising one. Commented Nov 17, 2010 at 23:39

1 Answer 1

10

Because you haven't initialized friends yet. It's still null.

You need to initialize it before using.

friends = new ArrayList<Friend>();

A common place to do this job is the class' constructor.

Sign up to request clarification or add additional context in comments.

13 Comments

No.... it doesn't works.... i put this: friends = new List<Friend>(); eclipse says: cannot instantiate the type List<Friend> lol, 7 guys up the wrong answer
Put on your glasses. I said ArrayList, not List. You obviously can't instantiate an interface. I'd suggest to stop temporarily with this all and redo the Java basics by a decent tutorial/book :)
but i dont wanna use arrayList.... i can't do with List? why ? i think i used List sometimes in the past, some years ago when i study
No, it's an interface, not a class. You need to use one of its implementations. ArrayList is the best choice for this particular purpose. Just do List<Friend> friends = new ArrayList<Friend>(). See also the Collections tutorial.
I think you've to learn about polymorphism and other basic OOP concepts as well :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.