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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With