-6

I want to make ArrayList of HashSet and use it.

**My Problem:**

I will get an Integer N as an user input.
I have to make a hashset and put some values in it.
Then add it to ArrayList and above step is to be done N times.
After it I have to check whether a element is present in the first/second/third/... or Nth hashset in ArrayList.

To check value in which hashset is also given by user.
I dont have to convert my ArrayList to hashset either I have to make ArrayList to hashset.

2 Answers2

4

Just make an ArrayList of HashSets :

ArrayList<HashSet<Integer>> list = new ArrayList<HashSet<Integer>>();

Then create HashSets, fill them, and put them in your ArrayList normally.

HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(whateverIntValue);
list.add(set);

You can then get the nth HashSet of your list using list.get(n).

Ephi
  • 346
  • 2
  • 12
1
List<Set<Integer>> sets = new ArrayList<>();

sets.add(someSet());
sets.add(someSet());
sets.add(someSet());

Set<Integer> someSet() {
    Set<Integer> set = new Hashset<>();
    Collections.addAll(set, 2, 3, 5, 7, 11);
    return set;
}

This makes a distinction between specification / interface of variables an method parameters and results, and implementation / implementing class.

So you can change the implementation, say to a sorted TreeSet without pain.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138