2

I am aware with the usage of transient in java.

The source code for TreeSet looks like this:

public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
/**
 * The backing map.
 */
private transient NavigableMap<E,Object> m;

// 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,Object> m) {
    this.m = 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 {@link Comparable} interface.
 * Furthermore, all such elements must be <i>mutually
 * comparable</i>: {@code e1.compareTo(e2)} must not throw a
 * {@code ClassCastException} for any elements {@code e1} and
 * {@code 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 {@code add} call will throw a
 * {@code ClassCastException}.
 */
public TreeSet() {
    this(new TreeMap<E,Object>());
}

Here, we observe that although reference is of type NaviagableMap the underlying data structure is TreeMap.

My question is why has it been marked transient ? Won't this lead to lose any TreeSet object its capability to be transported ?

Community
  • 1
  • 1
KNU
  • 2,560
  • 5
  • 26
  • 39
  • 1
    It uses its own `readObject` / `writeObject` methods (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/TreeSet.java#TreeSet.readObject%28java.io.ObjectInputStream%29). I guess that the reason is to provide more simple and compact serialized form. – Pavel Horal Jan 16 '15 at 07:52
  • 1
    The duplicate talks about HashMap, but the exact same pattern applies to TreeMap as well (and to ArrayList: http://stackoverflow.com/questions/9848129/why-does-arraylist-use-transient-storage?rq=1 ) – Thilo Jan 16 '15 at 07:54

0 Answers0