8

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.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Matécsa Andrea
  • 430
  • 5
  • 13

2 Answers2

7

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.

MC Emperor
  • 17,266
  • 13
  • 70
  • 106
1

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.

EmberTraveller
  • 355
  • 2
  • 16
  • Can you tell me than how I could solve my issue? What I do is the following: I have a lot of text to print out (I work on android) and want to give them colour. I already did it, but the amount of code is horrible and I wanted to shorten it with a function. now, for every part of my text I give a specific colour. That's why I thought about tupels, cause than I already tell for the function which part of the text it is. That's what I Need. Something to recognize easily what colour the Text should be and also Need that Information within code – Matécsa Andrea Sep 01 '17 at 13:32
  • @MatécsaAndrea It depends on how you color your string, you can split it in some amount of parts and then use substring() to get parts of string at specific indexes, depending the size of your string.Then you will know what parts have what color, because it will be decided by string's size. Or your could look for specific words in string, but then again, if you maintain the same string, it should be easy to find those words again. Alternatively you can create your own class where you will store information about colored parts in some way. Sorry, can't really do much without your implementation – EmberTraveller Sep 01 '17 at 13:53
  • thank you @EmberTraveller it was really helpful. I almost forgot to thank you :) – Matécsa Andrea Jul 08 '18 at 20:12
  • @MatécsaAndrea it's been almost a year lol. and you did thank me. I appreciate it a lot :) – EmberTraveller Jul 09 '18 at 09:08