Creating an array of Sets in Java

后端 未结 3 401
粉色の甜心
粉色の甜心 2021-02-02 15:13

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 R         


        
相关标签:
3条回答
  • 2021-02-02 15:18

    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;
    
    0 讨论(0)
  • 2021-02-02 15:19

    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.

    0 讨论(0)
  • 2021-02-02 15:28

    Arrays don't support Generics. Use an ArrayList:

    ArrayList<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
    
    0 讨论(0)
提交回复
热议问题