Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of pairs in Java

Tags:

java

arrays

I would like to initialize an Array of pairs but my way is not fully correct. Here how I first wrote it:

Pair<String, Integer>[] pair = new Pair[5];

It is accepted and it works but there is still the following warning:

"Unchecked assignment: 'android.util.Pair[]' to 'android.util.Pair<Java.lang.String, Java.lang.Integer>[]'...

I already tried to do like this:

Pair<String, Integer>[] pair = new Pair<String, Integer>[5];

but it doesn't work.

like image 447
Matécsa Andrea Avatar asked Sep 01 '17 11:09

Matécsa Andrea


2 Answers

It is because of the nature of generics.

My suggestion is to drop the idea of using arrays directly, and use a List<Pair<String, Integer>> instead. Under the hood, it uses an array anyway, but a List is more flexible.

List<Pair<String, Integer>> list = new ArrayList<Pair<String, Integer>>();
// You don't have to know its size on creation, it may resize dynamically

or shorter:

List<Pair<String, Integer>> list = new ArrayList<>();

You can then retrieve its elements using list.get(index) whereas you would use list[index] with an array.

like image 133
MC Emperor Avatar answered Nov 15 '22 17:11

MC Emperor


You can not create an array of generified type, in this case Pair. That's why your first solution works, because you did not specify the concrete type of Pair.

Technically, you can create an array, Generic arrays in Java, but it's not reccomended.

like image 30
EmberTraveller Avatar answered Nov 15 '22 17:11

EmberTraveller