0

I am trying to add an item to a list of card objects, and I get a nullpointer exception if I run this code. I believe I can't add to a 'null' list, but how do I fix this? (The error occurs at 'cards.add(...);')

public class Deck {

    private List<Card> cards;
    public Deck(String[] ranks, String[] suits, int[] values) {
        for (int i = 0; i < ranks.length; i++) {
            for (int j = 0; j < suits.length; j++){
                cards.add(new Card(ranks[i], suits[j], values[i]));
            }
        }
    }
Yuri
  • 13
  • 1
  • 2
  • 1
    You have declared `cards` as a reference to a `List`, but you have not assigned it to refer to any actual object. It looks like you want to create an appropriate object and assign a reference to it, maybe: `cards = new ArrayList<>();`. – John Bollinger Dec 06 '17 at 19:50
  • 2
    you never initialized `cards` – karakfa Dec 06 '17 at 19:50

2 Answers2

4

You need to initialize your list...

private List<Card> cards = new ArrayList<>();
Gaskoin
  • 2,469
  • 13
  • 22
2

Initialize the List cards as follows with the specified element type:

private List<Card> cards = new ArrayList<Card>();
Funsaized
  • 1,972
  • 4
  • 21
  • 41