how to check it
HashSet h=new HashSet();
h.add(123);
h.add(456);
h.add(789);
h.add(757);
h.add(989);
System.out.println( h.toArray(new String[2]));
how to check it
HashSet h=new HashSet();
h.add(123);
h.add(456);
h.add(789);
h.add(757);
h.add(989);
System.out.println( h.toArray(new String[2]));
First of all, you should not be using raw types like this. The HashSet
class is a generic class, and you should specify what the typ parameter should be.
What you are doing in your example is putting integers into the hashset. Therefore, you need to declare / initialize it as a HashSet<Integer>
like this:
HashSet<Integer> h = new HashSet<>();
Then, you extract the contents to an array, you should do this:
Integer[] a = h.toArray(new Integer[h.size()]);
and look at the first two elements.
There is no API that will allow you to extract just the first two elements as an array, but you could achieve this by allocating an array by hand and iterating the set to pull out the "first" two elements. (Noting of course that the order of the elements of a HashSet is unspecified ... so predicting which elements you will get is going to be difficult.)
You didn't say what error you experienced, but I expect it was an ArrayStoreException
. Your HashSet
contains Integer
objects and you cannot put an Integer
into an array of String
.
You are storing Integer values in your Set not Strings
This should work for you:
HashSet<Integer> h=new HashSet<>();
h.add(123);
h.add(456);
h.add(789);
h.add(757);
h.add(989);
System.out.println((new LinkedList<T>(h)).subList(0, 2));
But the order in the HashSet is not defind.