Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What issues / pitfalls must be considered when overriding equals and hashCode?
I'm sure there's a good reason, but could someone please explain why the java.util.Set interface lacks get(int Index), or any similar get() method? It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item from it. If I know I want the first item, I can use set.iterator().next(), but otherwise it seems I have to cast to an Array to retri...
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...
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...
As a followon to the discussion in the comments of this answer, should a TDD test always be made fail first? Consider the following example. If I am writing an implementation of LinkedHashSet and one test tests that after inserting a duplicate, the original is in the same iteration order as before the insert, I might want to add a separate test that the duplicate is not in the set at all. The...
I'm looking for a set-like container class that has these basic properties: has amortized O(1) insertion time, duplicate inserts are ignored has O(n) iteration time (specifically O(capacity) is not acceptable) reuses memory / only allocates when it exceeds current capacity The use-case is that I have a larger container of objects. During each loop I'll add a subset of those objects to this ...
I'm in the position of extending LinkedList and implement Set, so that I have a list with no duplicates. I'm wondering if such an implementation doesn't exist already? All I'm planning to do is to override the add(e) method to first look-up the element, and if present don't add it. Something like: add(E){ if(get(E) == null) super.add(E); }
I need a java data structure/solution that meets these requirements. What best fits these? 1) Object's insertion order must be kept 2) Object's must be unique (These are database objects that are uniquely identified by a UUID). 3) If a newer object with the same ID is added, the older version of the object should be over-written/removed 4) The Solution should be accessible by many thre...
How to design a latest recently used cache? Suppose that you have visited some items. You need to design a data structure to hold these items. Each item is associated with the latest visited time. Each time when you visit an item, check it in the data structure. If the item has been in the cache, update its visit time. Otherwise, insert it into the cache. The cache size is fixed, if it ...
All, I have been going through a lot of sites that post about the performance of various Collection classes for various actions i.e. adding an element, searching and deleting. But I also notice that all of them provide different environments in which the test was conducted i.e. O.S, memory, threads running etc. My question is, if there is any site/material that provides the same performance i...
Ive got one question. What happens when I try to add the "same" object twice to an ArrayList. With "the same" I mean an object of an individual class, which is identified as the same with equals() and hashCode(). It has different values for most of the member variables and was created from maybe different threads, but for equals() and hashCode() its the "same". Does the second object then repla...
I am retrieving a List from a JPA query, ordered by effectiveDate. There could be duplicate entries except for the date column, and I'll be ordering them most recent date first (desc). All I want in the set are all the entries with the newest effectiveDate; dupes with older effectiveDates are not allowed in the Set. If I create a HashSet by passing this List into the constructor, does the new ...
need an example on how to use a comparable class on a hashset to get an ascending order? Let say we have a hashset like: HashSet hs=new HashSet(); How can i get the hs to be in a ascending order??
I have an unsorted array, what is the best method to remove all the duplicates of an element if present? e.g: a[1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3] so after that operation the array should look like a[1,5,2,6,8,9,10,3,4,11]
If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed to be identical for every identical set of elements added, irrespective of the order in which they were added? Bonus question: what if the insertion order is identical as well? (Assuming Sun JDK6 with same HashSet initiali...
I am modeling a power subsystem in Java. A simple SQLite database contains a set of Line Replaceable Units (LRUs) and the connections between them. I am writing a Power Model API to simplify queries of the data store, using DDD patterns and repositories. I am seeking an appropriate Java collection to model the query results. There are some special cases in a LRU connection stream that have to...
I know this has be discussed over and over again here, but none of the examples I've tried worked for me. What I've got I access the Call log from Android and I get a list of all calls made. Of course, here I get a lot of duplicates. First I make a List List<ContactObject> lstContacts = new ArrayList<ContactObject>(); Then I add objects into it While (get some record in call ...
I need to recover the elements of a java Set collection interface in the same order they were passed into the set. How is it possible in java
I want to use a collection that is sorted, but one in which I can access elements by index, i.e. I want something that has characteristics of both a Set and a List. Java.util.TreeSet comes real close to what I need, but doesn't permit access via an index. I can think of several options: I could iterate through a TreeSet every time I needed a particular element. I could maintain a TreeSet an...
  /*
   * Copyright 2000-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;

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation:

     void foo(Set s) {
         Set copy = new LinkedHashSet(s);
         ...
     }
 
This technique is particularly useful if a module takes a set on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)

This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.

A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.

Note that this implementation is not synchronized. If multiple threads access a linked 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 LinkedHashSet(...));

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 will throw 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
Since:
1.4
See also:
java.lang.Object.hashCode()
Collection
Set
HashSet
TreeSet
Hashtable
public class LinkedHashSet<E>
    extends HashSet<E>
    implements Set<E>, Cloneablejava.io.Serializable {
    private static final long serialVersionUID = -2851667679971038690L;

    
Constructs a new, empty linked hash set with the specified initial capacity and load factor.

Parameters:
initialCapacity the initial capacity of the linked hash set
loadFactor the load factor of the linked hash set
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero, or if the load factor is nonpositive
    public LinkedHashSet(int initialCapacityfloat loadFactor) {
        super(initialCapacityloadFactortrue);
    }

    
Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).

Parameters:
initialCapacity the initial capacity of the LinkedHashSet
Throws:
java.lang.IllegalArgumentException if the initial capacity is less than zero
    public LinkedHashSet(int initialCapacity) {
        super(initialCapacity, .75f, true);
    }

    
Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
    public LinkedHashSet() {
        super(16, .75f, true);
    }

    
Constructs a new linked hash set with the same elements as the specified collection. The linked hash set is created with an initial capacity sufficient to hold the elements in the specified collection and the default load factor (0.75).

Parameters:
c the collection whose elements are to be placed into this set
Throws:
java.lang.NullPointerException if the specified collection is null
    public LinkedHashSet(Collection<? extends E> c) {
        super(Math.max(2*c.size(), 11), .75f, true);
        addAll(c);
    }
New to GrepCode? Check out our FAQ X