CaptainFuzzyFace
CaptainFuzzyFace

Reputation: 339

How to use List, ArrayList and/and Array to create a 2-dimensional array in Java

I'm fairly new to Java and having problems finding a structure to do the following.

I want a fixed length array. Each item to be a variable length array (or list) holding strings. So I've tried...

ArrayList<String>[] wordList = new ArrayList[maxWordLength];

I get a slapped wrist from Java for "Main.java uses unchecked or unsafe operations." and when I try to add an item I get "java.lang.NullPointerException"

wordList[oneWord.length()-1].add(oneWord);

How should I create my structure to keep Java happy?

Upvotes: 2

Views: 94

Answers (3)

Jeff Wang
Jeff Wang

Reputation: 1867

List is the interface that concrete classes such as ArrayList and LinkedList must implement.

ArrayList is a List that is optimized for sequential reading, and adding, and is backed by an internal array.

ArrayList<blah> or List<blah> is a List that contains objects that inherits blah (or if it is an interface, objects that implement it.)

ArrayList[] is actually an array of ArrayLists when you new ArrayList[x] that really means create an array of x length that contains ArrayLists. Each of the ArrayLists are not assigned, and so it's an uninitialized object, by default, it is null in many compilers but you can't depend on that.

So, let's say you create this fixed length array that contains a variable length list. you either have to do a loop over the array and say wordList[i] = new ArrayList<String>() or you have to do a nullcheck before you assign it and create a new ArrayList on each assignment

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

Java doesn't like arrays of generic types. (See Restrictions on Generics in the Java tutorials.) Instead, use a list of lists:

List<List<String>> wordList = new ArrayList<>(maxWordLength);

This creates a list with an initial capacity of maxWordLength that can contain lists of String. The initial size (as opposed to capacity) will be 0. Then you can add individual lists of strings to wordList. To avoid a NullPointerException later, you should fill wordList with empty lists to start with:

for (int i = 0; i < maxWordLength; i++) {
    wordList.add(new ArrayList<>());
}

Finally, you can add a word to a particular list in wordList with:

wordList.get(oneWord.length() - 1).add(oneWord);

This doesn't force wordList to be of fixed length, but otherwise should meet your requirements.

Upvotes: 4

Jackkobec
Jackkobec

Reputation: 6705

Keep it simple: Array with all elements as array of the Strings:

List<List<String>> listOfStringsArray = new ArrayList<>();

List<String> stringArray = Arrays.asList("String1", "String2");

listOfStringsArray.add(stringArray);

Upvotes: 0

Related Questions