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

2011/12/25

Why null pointer?

1
2
Builderboy2005 Builderboy2005

2011/12/27

#
If the list is null, trying to add an item onto the list will result in the Null pointer error you are getting. To fix this, you need to initilize the cards object like so:
cards = new List();
davmac davmac

2011/12/27

#
To clarify a little: you can't call a method on a null reference without getting a NullPointerException. With:
cards.add(card); 
... you are calling the "add" method on the "cards" reference. If cards is null then you are calling a method on a null reference. To put it another way, you can't add something to a list which doesn't exist. The list must exist first (as an empty list) before you can add something to it.
kiarocks kiarocks

2011/12/27

#
Oh, and this is a <Card> type of list. How to initialize that?
kiarocks kiarocks

2011/12/27

#
    List<Card> cards = new List();
Error: java.util.list is abstract, cannot be initiated.
Builderboy2005 Builderboy2005

2011/12/27

#
Oh whoops, forgot about that specific quirk. List itself is abstract, you will need to chose a specific type of List to initialize. For instance:
ArrayList<Card> cards = new ArrayList<Card>();
davmac davmac

2011/12/27

#
ArrayList<Card> cards = new AarrayList<Card>(); Should of course be: ArrayList<Card> cards = new ArrayList<Card>(); :) You can also do: List<Card> cards = new ArrayList<Card>();
kiarocks kiarocks

2011/12/27

#
Cool, it works. Just have to stop duplicates now.
You need to login to post a reply.
1
2