Initializing an array of pairs in Java

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.

Tags:

Java

Arrays