Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array of Sets in Java

Tags:

java

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 ?

like image 952
Belgi Avatar asked Nov 03 '11 17:11

Belgi


People also ask

How do you declare an array of sets in Java?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

Can we convert set to array in Java?

The toArray() method of Java Set is used to form an array of the same elements as that of the Set. Basically, it copies all the element from a Set to a new array.

What is array [] in Java?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application.


1 Answers

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.

like image 53
Mansoor Siddiqui Avatar answered Oct 11 '22 07:10

Mansoor Siddiqui