Initializing an array of pairs in Java

Matécsa Andrea :

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.

MC Emperor :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=477057&siteId=1