This site requires JavaScript, please enable it in your browser!
Greenfoot back
Pointifix
Pointifix wrote ...

2014/3/20

List Empty?

Pointifix Pointifix

2014/3/20

#
Hi. My Problem is that i want to add an object to an empty list, but when i do so it throws nullpointnerexception, whats my mistake?:
1
2
if(storeballs.isEmpty())storeballs.set(0,(BilliardBall)billiardball.get(i));
else storeballs.add((BilliardBall)billiardball.get(i));
bourne bourne

2014/3/20

#
You shouldn't need the if and else. You should be fine with just:
1
storeballs.add((BilliardBall)billiardball.get(i));
My guess is that billiardball or storeballs is not initiated.
Pointifix Pointifix

2014/3/20

#
how to initiate correctly? List storeballs = ?
bourne bourne

2014/3/20

#
Since List is an interface, you can't initialize as List, you can initialize it as something that implements List, such as ArrayList.
1
ArrayList<Ball> storeballs = new ArrayList<Ball>();
where Ball is your type. Might want to check this link out to learn about generics: http://docs.oracle.com/javase/tutorial/java/generics/why.html
Pointifix Pointifix

2014/3/20

#
jeah thanks alot ;)
You need to login to post a reply.