16

I'm new to Java so I'm probably doing something wrong here, I want to create an array of Sets and I get an error (from Eclipse). I have a class:

public class Recipient 
{
String name;
String phoneNumber;

public Recipient(String nameToSet, String phoneNumberToSet)
{
    name = nameToSet;
    phoneNumber = phoneNumberToSet;
}

void setName(String nameToSet)
{
    name = nameToSet;
}

void setPhoneNumber(String phoneNumberToSet)
{
    phoneNumber = phoneNumberToSet;
}

String getName()
{
    return name;
}

String getPhoneNumber()
{
    return phoneNumber;
}
}

and I'm trying to create an array:

Set<Recipient>[] groupMembers = new TreeSet<Recipient>[100]; 

The error I get is "Cannot create a generic array of TreeSet"

What is wrong ?

Belgi
  • 13,002
  • 21
  • 50
  • 63
  • 2
    Following SO question might be helpful. [http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation][1] [1]: http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation – Upul Bandara Nov 03 '11 at 17:29
  • I'm just curious: why on earth you need an array of Sets? – javagirl Nov 03 '11 at 17:35

3 Answers3

21

From http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html:

you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal).

Rather than using an array, you can use an ArrayList:

List<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();

The code above creates an empty ArrayList of Set<Recipient> objects. You would still have to instantiate every Set<Recipient> object that you put into the ArrayList.

Mansoor Siddiqui
  • 19,101
  • 9
  • 46
  • 65
  • I don't understand the first part of the answer: you wrote List[3] is both legal and illegal. what is the meaning of "unbounded wildcard " ? – Belgi Nov 03 '11 at 17:31
  • Apologies, stackoverflow was interpreting the generics (e.g. ``) as HTML tags. I have fixed the formatting. – Mansoor Siddiqui Nov 03 '11 at 17:32
  • thanks. I think you are missing > in , but its a very good answer. +1 – Belgi Nov 03 '11 at 17:36
0

Arrays don't support Generics. Use an ArrayList:

ArrayList<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
Brian Roach
  • 72,790
  • 10
  • 128
  • 154
0

You might want to consider using Guava's Multimap where the key is the index. This will handle creating the Sets for each index as you need them.

SetMultimap

SetMultimap<Integer, Recipient> groupMembers;
John B
  • 30,460
  • 6
  • 67
  • 92