Walt
Walt

Reputation: 111

Is it possible to make a List of arrays?

I have 3 arrays, 2 arrays of the type int, and one array of the type String.

My question is, is it possible to make a List that contains those 3 arrays?

I want to be able to do something like this: myList.get(0) which should give me the first array in the List.

Upvotes: 1

Views: 10851

Answers (1)

davidxxx
davidxxx

Reputation: 131396

That is possible but which value to add arrays of different types in a List ?
You will have to declare a List<Object> or List<Object[]>. So you lose the benefit of type safety as you have to cast the array or the array elements to manipulate other things as Object variables.

For example :

List<Object[]> list = new ArrayList<>();
list.add(new String[5]);
list.add(new Integer[5]);
Object[] objects = list.get(0);

You is stuck with an Object[].

To manipulate a more specific type you will have to perform downcast :

String[] objects = (String[]) list.get(0);

This will work but you can make an error such as :

Integer[] objects = (Integer[]) list.get(0);

And you would have the information only as an exception at runtime.

Note that using the instanceof operator before downcasting the array will not prevent malfunctioning of the program.

For example this will not rise a ClassCastException as the conditional statement will be evaluated to false :

if (list.get(0) instanceof Integer[]){
    Integer[] objects = (Integer[]) list.get(0);
    ...
}

But as consequence, it will never execute the processing. It is in a some way even worse as the issue could be not visible for the client.

And using a reversed logic will throw an exception as the initial code if the client uses incorrectly the list but is finally more verbose :

if (!(list.get(0) instanceof Integer[])){
    ... // throw exception
}

Integer[] objects = (Integer[]) list.get(0);

So definitely, you should forget the idea to add these arrays in a List.

Upvotes: 5

Related Questions