Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I'm a beginner in Java. Please suggest which collection(s) can/should be used for maintaining a sorted list in Java. I have tried Map and Set but they weren't what I was looking for.
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 may be teaching a "Java crash-course" soon. While it is probably safe to assume that the audience members will know Big-O notation, it is probably not safe to assume that they will know what the order of the various operations on various collection implementations is. I could take time to generate a summary matrix myself, but if it's already out there in the public domain somewhere, I'd sur...
What's the most efficient way to sort objects in an NSSet/NSMutableSet based on a property of the objects in the set? Right now the way I am doing it is by iterating through each object, add them to a NSMutableArray, and sort that array with NSSortDescriptor.
Pandigital number is a number that contains the digits 1..number length. For example 123, 4312 and 967412385. I have solved many Project Euler problems, but the Pandigital problems always exceed the one minute rule. This is my pandigital function: private boolean isPandigital(int n){ Set<Character> set= new TreeSet<Character>(); String string = n+""; for (char c:...
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...
I’m from a .NET background and now dabbling in Java. Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough): public void setTokens(Node node, int newTokens) { tokens.put(node, newTokens); } However, this code can fail for two reasons: User passes a null node. User passes an invalid node, i.e. one not c...
We have a requirement of reading/writing more than 10 million strings into a file. Also we do not want duplicates in the file. Since the strings would be flushed to a file as soon as they are read we are not maintaining it in memory. We cannot use hashcode because of collisions in the hash code due to which we might miss a string as duplicate. Two other approaches i found in my googling: 1.U...
From the Java 6 TreeSet<E> Documentation: boolean remove(Object o): Removes the specified element from this set if it is present. Why does this accept an Object instead of the generic type E? The only objects that can be added are of type E, so it follows that the only removable type should be of type E.
I'm making a turn-based RPG game, and my method that sorts all "Actor" objects in the order in which they all attack sorts them completely randomly. I, however, want to improve this method so that an "agility" stat that every actor has is able to improve their roll. I've looked at several methods in the Collections class, and Arrays as well, but didn't seem to find anything that does what I wan...
I have a list of objects say, List. The Entity class has an equals method,on few attributes ( business rule ) to differentiate one Entity object from the other. The task that we usually carry out on this list is to remove all the duplicates something like this : List<Entity> noDuplicates = new ArrayList<Entity>(); for(Entity entity: lstEntities) { int indexOf = noDuplicates.in...
Do you know of a popular library (apache collections, google collections, etc...) which has a reliable Java implementation for a Min-Max heap? I.e. a heap which allows to peek at its minimum and maximum value in O(1) and to remove at O(logn). I did a quick search and couldn't find one. Anyone know better?
I am doing a project in which I require btree or b+tree data structure. Does anyone know of an existing implementation of btree or b+tree (with insert, delete, search algorithms)? It should accept string as input and form btree or b+tree of these string.
Here is the piece of code that I have used for Java 5.0 TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ; Collections.reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated. Is there a more optimized way of doing it?
In my code, Java TreeSet iteration is the dominant time factor. In looking at the system I believe that it is O(n) complexity. Can anyone verify this? I am thinking that by providing links backward from child node to parent node I could improve the performance.
I'm accessing the minimum element of a binary tree lots of times. What implementations allow me to access the minimum element in constant time, rather than O(log n)?
Is there a method already provided in the Java 5 library to add an element to an alphabetical List? In other words, say I have a List<String> with three elements {"apple","cat","tree"} and I want to add the String "banana" while keeping the List in alphabetical order; is there an easy way to simply add it to the List, so that the List now has four elements {"apple","banana","cat","tree"}?
I'm trying to write a data structure which is a combination of Stack and HashSet with fast push/pop/membership (I'm looking for constant time operations). Think of Python's OrderedDict. I tried a few things and I came up with the following code: HashInt and SetInt. I need to add some documentation to the source, but basically I use a hash with linear probing to store indices in a vector of the...
  /*
   * Copyright 1998-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;

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Note that this implementation is not synchronized. If multiple threads access a tree 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.synchronizedSortedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

   SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

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.2
See also:
Collection
Set
HashSet
java.lang.Comparable
Comparator
TreeMap
 
 
 public class TreeSet<E> extends AbstractSet<E>
     implements NavigableSet<E>, Cloneablejava.io.Serializable
 {
    
The backing map.
 
     private transient NavigableMap<E,Objectm;
 
    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    
Constructs a set backed by the specified navigable map.
    TreeSet(NavigableMap<E,Objectm) {
        this. = m;
    }

    
Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the java.lang.Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException.
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

    
Constructs a new, empty tree set, sorted according to the specified comparator. All elements inserted into the set must be mutually comparable by the specified comparator: comparator.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint, the add call will throw a ClassCastException.

Parameters:
comparator the comparator that will be used to order this set. If null, the natural ordering of the elements will be used.
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<E,Object>(comparator));
    }

    
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the java.lang.Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.

Parameters:
c collection whose elements will comprise the new set
Throws:
java.lang.ClassCastException if the elements in c are not java.lang.Comparable, or are not mutually comparable
java.lang.NullPointerException if the specified collection is null
    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

Parameters:
s sorted set whose elements will comprise the new set
Throws:
java.lang.NullPointerException if the specified sorted set is null
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }

    
Returns an iterator over the elements in this set in ascending order.

Returns:
an iterator over the elements in this set in ascending order
    public Iterator<E> iterator() {
        return .navigableKeySet().iterator();
    }

    
Returns an iterator over the elements in this set in descending order.

Returns:
an iterator over the elements in this set in descending order
Since:
1.6
    public Iterator<E> descendingIterator() {
        return .descendingKeySet().iterator();
    }

    

Since:
1.6
    public NavigableSet<E> descendingSet() {
        return new TreeSet(.descendingMap());
    }

    
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 object to be checked for containment in this set
Returns:
true if this set contains the specified element
Throws:
java.lang.ClassCastException if the specified object cannot be compared with the elements currently in the set
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
    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 the 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
Throws:
java.lang.ClassCastException if the specified object cannot be compared with the elements currently in this set
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
    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 this set contained the specified element
Throws:
java.lang.ClassCastException if the specified object cannot be compared with the elements currently in this set
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
    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();
    }

    
Adds all of the elements in the specified collection to this set.

Parameters:
c collection containing elements to be added to this set
Returns:
true if this set changed as a result of the call
Throws:
java.lang.ClassCastException if the elements provided cannot be compared with the elements currently in the set
java.lang.NullPointerException if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator does not permit null elements
    public  boolean addAll(Collection<? extends E> c) {
        // Use linear-time version if applicable
        if (.size()==0 && c.size() > 0 &&
            c instanceof SortedSet &&
             instanceof TreeMap) {
            SortedSet<? extends E> set = (SortedSet<? extends E>) c;
            TreeMap<E,Objectmap = (TreeMap<E, Object>) ;
            Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
            Comparator<? super E> mc = map.comparator();
            if (cc==mc || (cc != null && cc.equals(mc))) {
                map.addAllForTreeSet(set);
                return true;
            }
        }
        return super.addAll(c);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
Since:
1.6
    public NavigableSet<E> subSet(E fromElementboolean fromInclusive,
                                  E toElement,   boolean toInclusive) {
        return new TreeSet<E>(.subMap(fromElementfromInclusive,
                                       toElement,   toInclusive));
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if toElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
Since:
1.6
    public NavigableSet<E> headSet(E toElementboolean inclusive) {
        return new TreeSet<E>(.headMap(toElementinclusive));
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
Since:
1.6
    public NavigableSet<E> tailSet(E fromElementboolean inclusive) {
        return new TreeSet<E>(.tailMap(fromElementinclusive));
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
    public SortedSet<E> subSet(E fromElement, E toElement) {
        return subSet(fromElementtruetoElementfalse);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if toElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
    public SortedSet<E> headSet(E toElement) {
        return headSet(toElementfalse);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromElement is null and this set uses natural ordering, or its comparator does not permit null elements
java.lang.IllegalArgumentException
    public SortedSet<E> tailSet(E fromElement) {
        return tailSet(fromElementtrue);
    }
    public Comparator<? super E> comparator() {
        return .comparator();
    }

    
    public E first() {
        return .firstKey();
    }

    
    public E last() {
        return .lastKey();
    }
    // NavigableSet API methods

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Since:
1.6
    public E lower(E e) {
        return .lowerKey(e);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Since:
1.6
    public E floor(E e) {
        return .floorKey(e);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Since:
1.6
    public E ceiling(E e) {
        return .ceilingKey(e);
    }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Since:
1.6
    public E higher(E e) {
        return .higherKey(e);
    }

    

Since:
1.6
    public E pollFirst() {
        Map.Entry<E,?> e = .pollFirstEntry();
        return (e == null)? null : e.getKey();
    }

    

Since:
1.6
    public E pollLast() {
        Map.Entry<E,?> e = .pollLastEntry();
        return (e == null)? null : e.getKey();
    }

    
Returns a shallow copy of this TreeSet instance. (The elements themselves are not cloned.)

Returns:
a shallow copy of this set
    public Object clone() {
        TreeSet<E> clone = null;
        try {
            clone = (TreeSet<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
        clone.m = new TreeMap<E,Object>();
        return clone;
    }

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

SerialData:
Emits the comparator used to order this set, or null if it obeys its elements' natural ordering (Object), followed by the size of the set (the number of elements it contains) (int), followed by all of its elements (each an Object) in order (as determined by the set's Comparator, or by the elements' natural ordering if the set has no Comparator).
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden stuff
        s.defaultWriteObject();
        // Write out Comparator
        s.writeObject(.comparator());
        // 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 TreeSet instance from a stream (that is, deserialize it).
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        // Read in any hidden stuff
        s.defaultReadObject();
        // Read in Comparator
        Comparator<? super E> c = (Comparator<? super E>) s.readObject();
        // Create backing TreeMap
        TreeMap<E,Objecttm;
        if (c==null)
            tm = new TreeMap<E,Object>();
        else
            tm = new TreeMap<E,Object>(c);
         = tm;
        // Read in size
        int size = s.readInt();
        tm.readTreeSet(sizes);
    }
    private static final long serialVersionUID = -2479143000061671589L;
New to GrepCode? Check out our FAQ X