Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What issues / pitfalls must be considered when overriding equals and hashCode?
I have the following java model class in AppEngine: public class Xyz ... { @Persistent private Set<Long> uvw; } When saving an object Xyz with an empty set uvw in Java, I get a "null" field (as listed in the appengine datastore viewer). When I try to load the same object in python (through remote_api), as defined by the following python model class: class Xyz(db.Model): uv...
The API for the Java Set interface states: For example, some implementations prohibit null elements, and some have restrictions on the types of their elements I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, Tree...
It's in Java. Basically I have about 1,000,000 strings, for each request I have to check a String is belonged to the list or not. I'm worried about the performance, so what's the best method? ArrayList? Hash? Thanks.
I'm looking for the appropriate algorithm to use to compare two files. I think I can do better than diff due to some added constraints. What I have are two text files each containing a list of files. They are snapshots of all the files on a system taken at two different times. I want to figure out which files have been added or deleted between the two snapshots. I could use diff to compare th...
OK, I have this problem to solve but I can’t program it in Java correctly. See the picture below, you’ll see a 6 pointed star were every point and intersection of lines is a letter. The assignment is to position the numbers 1 to 12 in such a way that the sum of all lines of four balls is 26 and the sum of all the 6 points of the star is 26 as well. This comes down to: (A+C+F+H==26) (A+D...
I have an Array of Objects that need the duplicates removed/filtered. I was going to just override equals & hachCode on the Object elements, and then stick them in a Set... but I figured I should at least poll stackoverflow to see if there was another way, perhaps some clever method of some other API?
I have a requirement to present highly structured information picked from a highly un-structured web service. In order to display the info correctly, I have to do a lot of String matches and duplicate removals to ensure I'm picking the right combination of elements. One of my challenges involves determining if a String is in an Array of Strings. My dream is to do "searchString.isIn(stringArr...
I'm looking for a implementation of java.util.Queue or something in the Google collection who behave like a Queue, but also ensure that each element of the queue is unique. (all further insertion will have no effect) It's that possible, or will I have to do it by hand? For now I'm using a Queue, with a LinkedList implementation, and I check the uniqueness before insertion. ( I use a side Map ...
I need to create a Set with initial values. Set<String> h = new HashSet<String>(); h.add("a"); h.add("b"); Is there a way to do it in one command? Thanks
In one of my Java 6 projects I have an array of LinkedHashMap instances as input to a method which has to iterate through all keys (i.e. through the union of the key sets of all maps) and work with the associated values. Not all keys exist in all maps and the method should not go through each key more than once or alter the input maps. My current implementation looks like this: Set<Object&...
I don't usually code in Java, but recently I started not having a choice. I might have some major misunderstanding of how to properly use HashSet. So it might be possible something I did is just plain wrong. However I'm grateful for any help, you might offer. So the actual problem: In a small program I was writing, I was generating very similar objects, which, when created, would have a very s...
final Multimap<Term, BooleanClause> terms = getTerms(bq); for (Term t : terms.keySet()) { Collection<BooleanClause> C = new HashSet(terms.get(t)); if (!C.isEmpty()) { for (Iterator<BooleanClause> it = C.iterator(); it.hasNext();) { BooleanClause c = it.next(); if(c.isSomething()) C.remove(c...
I'm looking for a structure which hashes keys without requiring a value. When queried, it should return true if the key is found and false otherwise. I'm looking for something similar to Hashtable<MyClass, Boolean> except insertion requires only a key and queries only ever return true or false, never null.
I have a large number of sets of numbers. Each set contains 10 numbers and I need to remove all sets that have 5 or more number (unordered) matches with any other set. For example: set 1: {12,14,222,998,1,89,43,22,7654,23} set 2: {44,23,64,76,987,3,2345,443,431,88} set 3: {998,22,7654,345,112,32,89,9842,31,23} Given the 3 sets of 10 numbers above sets 1 and sets 3 would be considered duplic...
In building Calendar application i have a spinner to display the list of synchronized accounts. The Code is given below... I get the list of synchronized accounts. But repitition of "Contacts' birthdays and events" and "Indian Holidays " are coming twice as below screenshot. MY CODE IS: final ContentResolver cr = ctx.getContentResolver(); Cursor cursor ; if (Integer.parseInt(Buil...
I found this statement if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception. at http://download.oracle.com/javase/6/docs/api/java/util/ConcurrentModificationException.html. I found the concurrent modification is even thrown in below code List<Employee> lista= new ArrayList(); Employee emp1...
I need to check in Java if a word consists of unique letters (case insensitive). As straight solution is boring, I came up with: For every char in a string check if indexOf(char) == lastIndexOf(char). Add all chars to HashSet and check if set size == string length. Convert a string to a char array, sort it alphabetically, loop through array elements and check if c[i] == c[i+1]. Currently I ...
I have two lists ( not java lists, you can say two columns) For example **List 1** **Lists 2** milan hafil dingo iga iga dingo elpha binga hafil mike meat dingo milan elpha meat iga neeta.peeta I'd like a method that returns how many elem...
Currently, I create a HashMap with Object Id as key and 1 as value. And the method asks for Object/Id and checks if there is a matching key. Is that ok? Or, is(are) there better alternative(s)?
I have an assignment to create an algorithm to find duplicates in an array which includes number values. but it has not said which kind of numbers, integers or floats. I have written the following pseudocode: FindingDuplicateAlgorithm(A) // A is the array mergeSort(A); for int i <- 0 to i<A.length if A[i] == A[i+1] i++ return A[i]...
  /*
   * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

   Set s = Collections.synchronizedSet(new HashSet(...));

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Parameters:
<E> the type of elements maintained by this set
Author(s):
Josh Bloch
Neal Gafter
Since:
1.2
See also:
Collection
Set
TreeSet
HashMap
 
 
 public class HashSet<E>
     extends AbstractSet<E>
     implements Set<E>, Cloneablejava.io.Serializable
 {
     static final long serialVersionUID = -5024744406713321676L;
 
     private transient HashMap<E,Objectmap;
 
     // Dummy value to associate with an Object in the backing Map
     private static final Object PRESENT = new Object();

    
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
    public HashSet() {
         = new HashMap<E,Object>();
    }

    
Constructs a new set containing the elements in the specified collection. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to contain the elements in the specified collection.

Parameters:
c the collection whose elements are to be placed into this set
Throws:
java.lang.NullPointerException if the specified collection is null
    public HashSet(Collection<? extends E> c) {
         = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

    
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified load factor.

Parameters:
initialCapacity the initial capacity of the hash map
loadFactor the load factor of the hash map
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive
    public HashSet(int initialCapacityfloat loadFactor) {
         = new HashMap<E,Object>(initialCapacityloadFactor);
    }

    
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load factor (0.75).

Parameters:
initialCapacity the initial capacity of the hash table
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero
    public HashSet(int initialCapacity) {
         = new HashMap<E,Object>(initialCapacity);
    }

    
Constructs a new, empty linked hash set. (This package private constructor is only used by LinkedHashSet.) The backing HashMap instance is a LinkedHashMap with the specified initial capacity and the specified load factor.

Parameters:
initialCapacity the initial capacity of the hash map
loadFactor the load factor of the hash map
dummy ignored (distinguishes this constructor from other int, float constructor.)
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive
    HashSet(int initialCapacityfloat loadFactorboolean dummy) {
         = new LinkedHashMap<E,Object>(initialCapacityloadFactor);
    }

    
Returns an iterator over the elements in this set. The elements are returned in no particular order.

Returns:
an Iterator over the elements in this set
See also:
ConcurrentModificationException
    public Iterator<E> iterator() {
        return .keySet().iterator();
    }

    
Returns the number of elements in this set (its cardinality).

Returns:
the number of elements in this set (its cardinality)
    public int size() {
        return .size();
    }

    
Returns true if this set contains no elements.

Returns:
true if this set contains no elements
    public boolean isEmpty() {
        return .isEmpty();
    }

    
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Parameters:
o element whose presence in this set is to be tested
Returns:
true if this set contains the specified element
    public boolean contains(Object o) {
        return .containsKey(o);
    }

    
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Parameters:
e element to be added to this set
Returns:
true if this set did not already contain the specified element
    public boolean add(E e) {
        return .put(e)==null;
    }

    
Removes the specified element from this set if it is present. More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this set contains such an element. Returns true if this set contained the element (or equivalently, if this set changed as a result of the call). (This set will not contain the element once the call returns.)

Parameters:
o object to be removed from this set, if present
Returns:
true if the set contained the specified element
    public boolean remove(Object o) {
        return .remove(o)==;
    }

    
Removes all of the elements from this set. The set will be empty after this call returns.
    public void clear() {
        .clear();
    }

    
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.

Returns:
a shallow copy of this set
    public Object clone() {
        try {
            HashSet<E> newSet = (HashSet<E>) super.clone();
            newSet.map = (HashMap<E, Object>) .clone();
            return newSet;
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

    
Save the state of this HashSet instance to a stream (that is, serialize it).

SerialData:
The capacity of the backing HashMap instance (int), and its load factor (float) are emitted, followed by the size of the set (the number of elements it contains) (int), followed by all of its elements (each an Object) in no particular order.
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();
        // Write out HashMap capacity and load factor
        s.writeInt(.capacity());
        s.writeFloat(.loadFactor());
        // Write out size
        s.writeInt(.size());
        // Write out all elements in the proper order.
        for (Iterator i=.keySet().iterator(); i.hasNext(); )
            s.writeObject(i.next());
    }

    
Reconstitute the HashSet instance from a stream (that is, deserialize it).
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();
        // Read in HashMap capacity and load factor and create backing HashMap
        int capacity = s.readInt();
        float loadFactor = s.readFloat();
         = (((HashSet)thisinstanceof LinkedHashSet ?
               new LinkedHashMap<E,Object>(capacityloadFactor) :
               new HashMap<E,Object>(capacityloadFactor));
        // Read in size
        int size = s.readInt();
        // Read in all elements in the proper order.
        for (int i=0; i<sizei++) {
            E e = (E) s.readObject();
            .put(e);
        }
    }
New to GrepCode? Check out our FAQ X