-1

I'm trying to add objects to my ArrayList coupleList but I keep getting the error.

Constructor for my WordCouple class

    public class WordCouple {

    private String first;
    private String second;

    public WordCouple (String first, String second) {
        first = this.first;
        second = this.second;
    }

Constructor for my WordCoupleList class

import java.util.ArrayList;
public class WordCoupleList {

    private ArrayList<WordCouple> coupleList;


    public WordCoupleList(String[] words) {


        for(int i = 0; i < words.length -1; i ++) {
            for(int j = i+1; j < words.length; j++) {


                coupleList.add(new WordCouple(words[i], words[i+j]));

            }
        }

    }

What I'm trying to do is make all possible WordCouple instances from a String array, and place them in an ArrayList but I can't seem to initialize the ArrayList.

Example: the WordCoupleList constructor was passed an array like: {dog, cat, the ,cat} then the ArrayList would look like [(dog,cat), (dog,the), (dog,cat), (cat,the), (cat,cat), (the,cat). Each word in the array must make a couple with the other words that exist later in the array.

joonghyup cha
  • 624
  • 3
  • 12

1 Answers1

6

Because

private ArrayList<WordCouple> coupleList;

declares a variable of type ArrayList but does not initialize it (so it is null). You need something like

private ArrayList<WordCouple> coupleList = new ArrayList<>();

or, better, prefer the List interface like

private List<WordCouple> coupleList = new ArrayList<>();

or just initialize it in your constructor. Like,

public WordCoupleList(String[] words) {
    coupleList = new ArrayList<>();
    for (int i = 0; i < words.length - 1; i++) {
        for (int j = i + 1; j < words.length; j++) {
            coupleList.add(new WordCouple(words[i], words[i + j]));
        }
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249