0

I am trying to declare an array of Set<String> so I do not have to manage each sets separately. But things go wrong:

      ArrayList<Set<String>> categories=new LinkedHashSet<>();

Here, Java says that type Set<String> is erroneous and then reports an error.

If this is wrong, then how can I make an array of :

static  Set<String> category1 = new LinkedHashSet<>();
4
  • A LinkedHashSet is not an ArrayList of anything. Commented Dec 15, 2015 at 2:12
  • I don't think this works. You have to manage the Sets individually. If that's a pain, make your own ListSet class and encapsulate the management. Commented Dec 15, 2015 at 2:14
  • @markspace that is exactly what I am trying to avoid. I dislike to individually manage each set and I thought there is a way to make an array of them so can manage all together? Commented Dec 15, 2015 at 2:19
  • I'm like 99.99% sure there is no way to do what you want. You'll just have to write some code to do it for you. Commented Dec 15, 2015 at 2:19

2 Answers 2

2

You are initialising an ArrayList with LinkedHashSet object and hence the error:

  ArrayList<Set<String>> categories=new LinkedHashSet<>();

change it to

  ArrayList<Set<String>> categories=new ArrayList<>();

you need to use HashSet when you create a Set to be added into the list. Something like this:

      Set<String> firstSet = new HashSet<String>();
      //build your set 
      //add set to list
      categories.add(firstSet);

Btw, you mentioned Array in your question description, so here is the declaraiton for plain array of Sets:

      Set<String>[] categories=new HashSet[10];
Sign up to request clarification or add additional context in comments.

5 Comments

But then I have to make all Sets individually which is painful.
@lonesome It's the only way. Java doesn't automagically make classes for you like you are envisioning.
@lonesome You will need to initialize all elements that needed to be added to a collection. They cannot be autoinitialized. To reduce the task, you may write methods to build your Set(s)
So what is the difference between Set<String>[] and ArrayList<Set<String>>?
@lonesome Read your course book again for difference between arraylist and array
0

You can do something like:

List<HashSet> list =new ArrayList<HashSet>();
HashSet<String> hs =new HashSet<String>();
hs.add(value1);
hs.add(value2);
list.add(hs);

You can use for or while loop to add values to set(hs) and then add the set to list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.