Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If only one element in a hashset, how can I get it out?

Tags:

java

hashset

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];
}
like image 270
cow12331 Avatar asked May 11 '14 17:05

cow12331


People also ask

Is it possible to retrieve a single element from Set?

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.

Does HashSet have a get method?

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.


1 Answers

set.iterator().next()

Do so only if you are sure there is an element in the set. Otherwise next() will throw an exception.

like image 94
theHacker Avatar answered Nov 02 '22 23:11

theHacker