HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
How can I get the 1
out? I can do it by for(integer i : set)
. Do you have another idea to solve the problem?
My specified problem is "Given an array of integers, every element appears twice except for one. Find that single one." I want to use add elements into set if the set doesn't contain it and remove existed element during loop. And the last remain element is answer. I don't know how to return it.
public static int singleNumber(int[] A) {
HashSet<Integer> set = new HashSet<Integer>();
for (int a : A) {
if (!set.contains(a)) {
set.add(a);
} else {
set.remove(a);
}
}
/**
* for(Integer i : set) { return i; }
*return A[0];//need one useless return
/**
* while(set.iterator().hasNext()) { return set.iterator().next(); }
* return A[0];//need one useless return
*/
return set.toArray(new Integer[1])[0];
}
You can use an Iterator to both obtain the only element as well as verify that the collection only contains one element (thereby avoiding the size() call and the unnecessary list creation): Iterator<Element> iterator = set.
HashSet does not have a get method to retrieve elements. HashSet implements the Set interface. The Set is a collection with no duplicates. This interface models the mathematical set abstraction.
set.iterator().next()
Do so only if you are sure there is an element in the set. Otherwise next()
will throw an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With