A TreeSet is an implementation of interface
Set that stores the elements in their natural order or, optionally, in a user-defined order. It implements the NavigableSet interface, which provides numerous methods for working with the set in terms of the order of the elements.
package collections.sets;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableSet;
import java.util.SortedSet;
import java.util.TreeSet;
public class UsingTreeSet {
public static void main(String[] args) {
// Using the
TreeSet<String> set = new TreeSet<>(List.of("A", "C", "B")); // [A,B,C]
// Using a user-defined order, e.g., case insensitive
set = new TreeSet<>();
set.addAll(List.of("A", "b", "C")); // [A,b,C]
// Using a custom comparator for the user-defined order by length
set = new TreeSet<>();
set.addAll(List.of("AA", "B", "CCC")); // [B, AA, CCC]
// Modifying the set
set = new TreeSet<>(List.of("C","B")); // [B,C]
set.add("A"); // [A,B,C]
set.add("D"); // [A,B,C,D]
String letter = set.removeFirst(); // [B,C,D]
letter = set.removeLast(); // [B,C]
// set.addFirst("A"); //
// the set
set = new TreeSet<>(List.of("d","b","a","e","c")); // [a,b,c,d,e]
String first = set.first(); // -> a
String last = set.last(); // -> e
String lower = set.lower("c"); // -> b
String floor = set.floor("c"); // -> c
String ceiling = set.ceiling("c"); // -> c
String higher = set.higher("c"); // -> d
// Producing subsets
SortedSet<String> head = set.headSet("c"); // [a,b]
SortedSet<String> tail = set.tailSet("c"); // [c,d,e]
SortedSet<String> subset = set.subSet("b", "d"); // [b,c]
// Removing elements
set.pollFirst(); // [b,c,d,e] -> a
set.removeFirst(); // [c,d,e] -> b
// See also pollLast and removeLast
// Working with the reverse order: iterators and descending sets
set = new TreeSet<>(List.of("d","b","a","e","c")); // [a,b,c,d,e]
for (Iterator<String> iterator = set.descendingIterator(); iterator.hasNext(); ) {
System.out.println(iterator.next());
}
NavigableSet<String> reversed = set.descendingSet();
for (String letter2 : reversed) {
System.out.println(letter2);
}
last = reversed.first(); // -> e
}
}
By default, a TreeSet will keep its elements sorted by their natural order,
the order defined by their compareTo method. If the set element is of a type that
does not implement the Comparable
interface, attempting to add elements to the set will result in a ClassCastException.
By default, a TreeSet will keep its elements sorted by their natural order,
the order defined by their compareTo method. If the set element is of a type that
does not implement the Comparable
interface, attempting to add elements to the set will result in a ClassCastException.
To initialize a TreeSet to use its elements' natural order, it's also possible
to use the class's default constructor followed by calls to the add or
addAll method.
TreeSet<String> set = new TreeSet<>();
set.add("A");
// etc.
To initialize a TreeSet to use its elements' natural order, it's also possible
to use the class's default constructor followed by calls to the add or
addAll method.
TreeSet<String> set = new TreeSet<>();
set.add("A");
// etc.
A descending set is best suited when you need to query or manipulate the elements in the reverse order. The descending set returned is a of the original set.
A descending set is best suited when you need to query or manipulate the elements in the reverse order. The descending set returned is a of the original set.
To specify an order other than the natural order, use the constructor that
takes a Comparator as argument.
This Comparator object defines the order.
To specify an order other than the natural order, use the constructor that
takes a Comparator as argument.
This Comparator object defines the order.
This code uses a lambda expression to create an
instance of Comparator<String>. Another, more advanced, option is to use the Comparator's comparing factory method
together with a method reference:
set = new TreeSet<>(Comparator.comparing(String::length);
This code uses a lambda expression to create an
instance of Comparator<String>. Another, more advanced, option is to use the Comparator's comparing factory method
together with a method reference:
set = new TreeSet<>(Comparator.comparing(String::length);
In a TreeSet, the order of the elements is specified through the constructor.
Methods addFirst and addLast are thus inapplicable and calling them will
result in an exception.
In a TreeSet, the order of the elements is specified through the constructor.
Methods addFirst and addLast are thus inapplicable and calling them will
result in an exception.
This group of methods are pure functions. They have no side-effect, namely, they leave the target tree-set object unchanged.
This group of methods are pure functions. They have no side-effect, namely, they leave the target tree-set object unchanged.
Methods lower, floor, ceiling, and higher return the element in the set which is, respectively,
strictly lower, lower or equal, greater or equal, or strictly greater than the argument.
This pair of methods both remove the first element from the set and return it.
The only difference is how they handle an empty set. pollFirst returns null
whereas removeFirst throws a NoSuchElementException. There exists a similar
pair of methods pollLast and removeLast.
This pair of methods both remove the first element from the set and return it.
The only difference is how they handle an empty set. pollFirst returns null
whereas removeFirst throws a NoSuchElementException. There exists a similar
pair of methods pollLast and removeLast.
A descending iterator is best suited when you only need to iterate through the elements in descending order once.
A descending iterator is best suited when you only need to iterate through the elements in descending order once.
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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.c - collection whose elements will comprise the new setClassCastException - if the elements in c are
not Comparable, or are not mutually comparableNullPointerException - if the specified collection is nullNavigableSet 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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.comparator - the comparator that will be used to order this set.
If null, the natural
ordering of the elements will be used.Class String provides, as a constant, a reference to a predefined comparator to compare strings in a case-insensitive manner.
String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
String objects as by
compareToIgnoreCase.
This comparator is serializable.
String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2, 3);
String d = cde.substring(1, 2);
The class String includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null argument to a constructor
or method in this class will cause a NullPointerException to be
thrown.
A String represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character class for
more information).
Index values refer to char code units, so a supplementary
character uses two positions in a String.
The String class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator class provides methods for
finer-grain, locale-sensitive String comparison.
javac compiler
may implement the operator with StringBuffer, StringBuilder,
or java.lang.invoke.StringConcatFactory depending on the JDK version. The
implementation of string conversion is typically through the method toString,
defined by Object and inherited by all classes in Java.String objects as by
compareToIgnoreCase.
This comparator is serializable.
Note that this Comparator does not take locale into account,
and will result in an unsatisfactory ordering for certain locales.
The Collator class provides locale-sensitive comparison.
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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.comparator - the comparator that will be used to order this set.
If null, the natural
ordering of the elements will be used.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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.c - collection whose elements will comprise the new setClassCastException - if the elements in c are
not Comparable, or are not mutually comparableNullPointerException - if the specified collection is nullNavigableSet 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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.c - collection whose elements will comprise the new setClassCastException - if the elements in c are
not Comparable, or are not mutually comparableNullPointerException - if the specified collection is nullNavigableSet 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.
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.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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
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.c - collection whose elements will comprise the new setClassCastException - if the elements in c are
not Comparable, or are not mutually comparableNullPointerException - if the specified collection is nullA view is an object that presents the state of another object. If the original object is modified, this modification becomes visible in the view object. For example:
List<String> list = new ArrayList<>(List.of("a","b","c"));
List<String> view = Collections.unmodifiableList(list);
list.removeFirst();
System.out.println(view); // -> [b,c]
A view is an object that presents the state of another object. If the original object is modified, this modification becomes visible in the view object. For example:
List<String> list = new ArrayList<>(List.of("a","b","c"));
List<String> view = Collections.unmodifiableList(list);
list.removeFirst();
System.out.println(view); // -> [b,c]
Unlike sets, lists typically allow duplicate elements. More formally,
lists typically allow pairs of elements e1 and e2
such that e1.equals(e2), and they typically allow multiple
null elements if they allow null elements at all. It is not inconceivable
that someone might wish to implement a list that prohibits duplicates, by
throwing runtime exceptions when the user attempts to insert them, but we
expect this usage to be rare.
The List interface places additional stipulations, beyond those
specified in the Collection interface, on the contracts of the
iterator, add, remove, equals, and
hashCode methods. Declarations for other inherited methods are
also included here for convenience.
The List interface provides four methods for positional (indexed)
access to list elements. Lists (like Java arrays) are zero based. Note
that these operations may execute in time proportional to the index value
for some implementations (the LinkedList class, for
example). Thus, iterating over the elements in a list is typically
preferable to indexing through it if the caller does not know the
implementation.
The List interface provides a special iterator, called a
ListIterator, that allows element insertion and replacement, and
bidirectional access in addition to the normal operations that the
Iterator interface provides. A method is provided to obtain a
list iterator that starts at a specified position in the list.
The List interface provides two methods to search for a specified
object. From a performance standpoint, these methods should be used with
caution. In many implementations they will perform costly linear
searches.
The List interface provides two methods to efficiently insert and
remove multiple elements at an arbitrary point in the list.
Note: While it is permissible for lists to contain themselves as elements,
extreme caution is advised: the equals and hashCode
methods are no longer well defined on such a list.
Some list implementations have restrictions on the elements that
they may contain. For example, some implementations prohibit null elements,
and some have restrictions on the types of their elements. Attempting to
add an ineligible element throws an unchecked exception, typically
NullPointerException or ClassCastException. Attempting
to query the presence of an ineligible element may throw an exception,
or it may simply return false; some implementations will exhibit the former
behavior and some will exhibit the latter. More generally, attempting an
operation on an ineligible element whose completion would not result in
the insertion of an ineligible element into the list may throw an
exception or it may succeed, at the option of the implementation.
Such exceptions are marked as "optional" in the specification for this
interface.
The List.of and
List.copyOf static factory methods
provide a convenient way to create unmodifiable lists. The List
instances created by these methods have the following characteristics:
UnsupportedOperationException to be thrown.
However, if the contained elements are themselves mutable,
this may cause the List's contents to appear to change.
null elements. Attempts to create them with
null elements result in NullPointerException.
subList views implement the
RandomAccess interface.
This interface is a member of the Java Collections Framework.
E - the List's element typee1 - the first elemente2 - the second elemente3 - the third elementList containing the specified elementsNullPointerException - if an element is nullremoveFirst in interface SequencedCollection<E>removeFirst in interface SortedSet<E>pollFirst method. Otherwise, it throws NoSuchElementException.NoSuchElementException - if this collection is emptyUnsupportedOperationException - if this collection implementation
does not support this operationremoveLast in interface SequencedCollection<E>removeLast in interface SortedSet<E>pollLast method. Otherwise, it throws NoSuchElementException.NoSuchElementException - if this collection is emptyUnsupportedOperationException - if this collection implementation
does not support this operationE - the List's element typee1 - the first elemente2 - the second elemente3 - the third elemente4 - the fourth elemente5 - the fifth elementList containing the specified elementsNullPointerException - if an element is nullfirst in interface SortedSet<E>NoSuchElementException - if this set is emptylast in interface SortedSet<E>NoSuchElementException - if this set is emptynull if there is no such element.null if there is no such element.lower in interface NavigableSet<E>e - the value to matche,
or null if there is no such elementClassCastException - if the specified element cannot be
compared with the elements currently in the setNullPointerException - if the specified element is null
and this set uses natural ordering, or its comparator
does not permit null elementsnull if there is no such element.null if there is no such element.floor in interface NavigableSet<E>e - the value to matche,
or null if there is no such elementClassCastException - if the specified element cannot be
compared with the elements currently in the setNullPointerException - if the specified element is null
and this set uses natural ordering, or its comparator
does not permit null elementsnull if there is no such element.null if there is no such element.ceiling in interface NavigableSet<E>e - the value to matche,
or null if there is no such elementClassCastException - if the specified element cannot be
compared with the elements currently in the setNullPointerException - if the specified element is null
and this set uses natural ordering, or its comparator
does not permit null elementsnull if there is no such element.null if there is no such element.higher in interface NavigableSet<E>e - the value to matche,
or null if there is no such elementClassCastException - if the specified element cannot be
compared with the elements currently in the setNullPointerException - if the specified element is null
and this set uses natural ordering, or its comparator
does not permit null elementstoElement. The returned set is
backed by this set, so changes in the returned set are
reflected in this set, and vice-versa. The returned set
supports all optional set operations that this set supports.
toElement. The returned set is
backed by this set, so changes in the returned set are
reflected in this set, and vice-versa. The returned set
supports all optional set operations that this set supports.
The returned set will throw an IllegalArgumentException
on an attempt to insert an element outside its range.
Equivalent to headSet(toElement, false).
headSet in interface NavigableSet<E>headSet in interface SortedSet<E>toElement - high endpoint (exclusive) of the returned settoElementClassCastException - if toElement is not compatible
with this set's comparator (or, if the set has no comparator,
if toElement does not implement Comparable).
Implementations may, but are not required to, throw this
exception if toElement cannot be compared to elements
currently in the set.NullPointerException - if toElement is null
and this set uses natural ordering, or its comparator does
not permit null elementsIllegalArgumentException - if this set itself has a
restricted range, and toElement lies outside the
bounds of the rangeNavigableSet 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.
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.
The addFirst and addLast methods of this class
throw UnsupportedOperationException. The encounter order of elements is determined
by the comparison method; therefore, explicit positioning is not supported.
This class is a member of the Java Collections Framework.
Set that further provides a total ordering on its elements.
The elements are ordered using their natural
ordering, or by a Comparator typically provided at sorted
set creation time. The set's iterator will traverse the set in
ascending element order. Several additional operations are provided
to take advantage of the ordering. (This interface is the set
analogue of SortedMap.)
Set that further provides a total ordering on its elements.
The elements are ordered using their natural
ordering, or by a Comparator typically provided at sorted
set creation time. The set's iterator will traverse the set in
ascending element order. Several additional operations are provided
to take advantage of the ordering. (This interface is the set
analogue of SortedMap.)
All elements inserted into a sorted set must implement the Comparable
interface (or be accepted by the specified comparator). Furthermore, all
such elements must be mutually comparable: e1.compareTo(e2)
(or comparator.compare(e1, e2)) must not throw a
ClassCastException for any elements e1 and e2 in
the sorted set. Attempts to violate this restriction will cause the
offending method or constructor invocation to throw a
ClassCastException.
Note that the ordering maintained by a sorted set (whether or not an
explicit comparator is provided) must be consistent with equals if
the sorted set is to correctly implement the Set interface. (See
the Comparable interface or Comparator interface 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 sorted set 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 sorted set,
equal. The behavior of a sorted set is well-defined even if its
ordering is inconsistent with equals; it just fails to obey the general
contract of the Set interface.
All general-purpose sorted set implementation classes should
provide four "standard" constructors: 1) A void (no arguments)
constructor, which creates an empty sorted set sorted according to
the natural ordering of its elements. 2) A constructor with a
single argument of type Comparator, which creates an empty
sorted set sorted according to the specified comparator. 3) A
constructor with a single argument of type Collection,
which creates a new sorted set with the same elements as its
argument, sorted according to the natural ordering of the elements.
4) A constructor with a single argument of type SortedSet,
which creates a new sorted set with the same elements and the same
ordering as the input sorted set. There is no way to enforce this
recommendation, as interfaces cannot contain constructors.
Note: several methods return subsets with restricted ranges.
Such ranges are half-open, that is, they include their low
endpoint but not their high endpoint (where applicable).
If you need a closed range (which includes both endpoints), and
the element type allows for calculation of the successor of a given
value, merely request the subrange from lowEndpoint to
successor(highEndpoint). For example, suppose that s
is a sorted set of strings. The following idiom obtains a view
containing all of the strings in s from low to
high, inclusive:
SortedSet<String> sub = s.subSet(low, high+"\0");A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the Strings in
s from low to
high, exclusive:SortedSet<String> sub = s.subSet(low+"\0", high);
This interface is a member of the Java Collections Framework.
fromElement. The returned
set is backed by this set, so changes in the returned set are
reflected in this set, and vice-versa. The returned set
supports all optional set operations that this set supports.
fromElement. The returned
set is backed by this set, so changes in the returned set are
reflected in this set, and vice-versa. The returned set
supports all optional set operations that this set supports.
The returned set will throw an IllegalArgumentException
on an attempt to insert an element outside its range.
Equivalent to tailSet(fromElement, true).
tailSet in interface NavigableSet<E>tailSet in interface SortedSet<E>fromElement - low endpoint (inclusive) of the returned setfromElementClassCastException - if fromElement is not compatible
with this set's comparator (or, if the set has no comparator,
if fromElement does not implement Comparable).
Implementations may, but are not required to, throw this
exception if fromElement cannot be compared to elements
currently in the set.NullPointerException - if fromElement is null
and this set uses natural ordering, or its comparator does
not permit null elementsIllegalArgumentException - if this set itself has a
restricted range, and fromElement lies outside the
bounds of the rangefromElement, inclusive, to toElement,
exclusive. (If fromElement and toElement are
equal, the returned set is empty.) The returned set is backed
by this set, so changes in the returned set are reflected in
this set, and vice-versa. The returned set supports all
optional set operations that this set supports.
fromElement, inclusive, to toElement,
exclusive. (If fromElement and toElement are
equal, the returned set is empty.) The returned set is backed
by this set, so changes in the returned set are reflected in
this set, and vice-versa. The returned set supports all
optional set operations that this set supports.
The returned set will throw an IllegalArgumentException
on an attempt to insert an element outside its range.
Equivalent to subSet(fromElement, true, toElement, false).
subSet in interface NavigableSet<E>subSet in interface SortedSet<E>fromElement - low endpoint (inclusive) of the returned settoElement - high endpoint (exclusive) of the returned setfromElement, inclusive, to toElement, exclusiveClassCastException - if fromElement and
toElement cannot be compared to one another using this
set's comparator (or, if the set has no comparator, using
natural ordering). Implementations may, but are not required
to, throw this exception if fromElement or
toElement cannot be compared to elements currently in
the set.NullPointerException - if fromElement or
toElement is null and this set uses natural ordering,
or its comparator does not permit null elementsIllegalArgumentException - if fromElement is
greater than toElement; or if this set itself
has a restricted range, and fromElement or
toElement lies outside the bounds of the rangenull if this set is empty.null if this set is empty.pollFirst in interface NavigableSet<E>null if this set is emptyNoSuchElementException - if the iteration has no more elementsSystem class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.System class contains several useful class fields
and methods. It cannot be instantiated.
Among the facilities provided by the System class
are standard input, standard output, and error output streams;
access to externally defined properties and environment
variables; a means of loading files and libraries; and a utility
method for quickly copying a portion of an array.Console.charset() if the Console exists,
stdout.encoding otherwise.
Console.charset() if the Console exists,
stdout.encoding otherwise.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
See the println methods in class PrintStream.
print(String) and then
println().print(String) and then
println().x - The String to be printed.true if the iteration has more elements.
(In other words, returns true if next() would
return an element rather than throwing an exception.)true if the iteration has more elements.
(In other words, returns true if next() would
return an element rather than throwing an exception.)true if the iteration has more elementsdescendingIterator in interface NavigableSet<E>Iterator takes the place of
Enumeration in the Java Collections Framework. Iterators
differ from enumerations in two ways:
Iterator takes the place of
Enumeration in the Java Collections Framework. Iterators
differ from enumerations in two ways:
This interface is a member of the Java Collections Framework.
Enumeration can be converted into an Iterator by
using the Enumeration.asIterator() method.remove operation), the results of
the iteration are undefined.
remove operation), the results of
the iteration are undefined.
The returned set has an ordering equivalent to
Collections.reverseOrder(comparator()).
The expression s.descendingSet().descendingSet() returns a
view of s essentially equivalent to s.
descendingSet in interface NavigableSet<E>SortedSet extended with navigation methods reporting
closest matches for given search targets. Methods lower(E),
floor(E), ceiling(E), and higher(E) return elements
respectively less than, less than or equal, greater than or equal,
and greater than a given element, returning null if there
is no such element.
SortedSet extended with navigation methods reporting
closest matches for given search targets. Methods lower(E),
floor(E), ceiling(E), and higher(E) return elements
respectively less than, less than or equal, greater than or equal,
and greater than a given element, returning null if there
is no such element.
A NavigableSet may be accessed and traversed in either
ascending or descending order. The descendingSet() method
returns a view of the set with the senses of all relational and
directional methods inverted. The performance of ascending
operations and views is likely to be faster than that of descending
ones. This interface additionally defines methods pollFirst() and pollLast() that return and remove the lowest
and highest element, if one exists, else returning null.
Methods
subSet(E, boolean, E, boolean),
headSet(E, boolean), and
tailSet(E, boolean)
differ from the like-named SortedSet methods in accepting
additional arguments describing whether lower and upper bounds are
inclusive versus exclusive. Subsets of any NavigableSet
must implement the NavigableSet interface.
The return values of navigation methods may be ambiguous in
implementations that permit null elements. However, even
in this case the result can be disambiguated by checking
contains(null). To avoid such issues, implementations of
this interface are encouraged to not permit insertion of
null elements. (Note that sorted sets of Comparable elements intrinsically do not permit null.)
Methods
subSet(E, E),
headSet(E), and
tailSet(E)
are specified to return SortedSet to allow existing
implementations of SortedSet to be compatibly retrofitted to
implement NavigableSet, but extensions and implementations
of this interface are encouraged to override these methods to return
NavigableSet.
This interface is a member of the Java Collections Framework.
NoSuchElementException - if this set is emptyString class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
Here are some more examples of how strings can be used:
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2, 3);
String d = cde.substring(1, 2);
The class String includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null argument to a constructor
or method in this class will cause a NullPointerException to be
thrown.
A String represents a string in the UTF-16 format
in which supplementary characters are represented by surrogate
pairs (see the section Unicode
Character Representations in the Character class for
more information).
Index values refer to char code units, so a supplementary
character uses two positions in a String.
The String class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., char values).
Unless otherwise noted, methods for comparing Strings do not take locale
into account. The Collator class provides methods for
finer-grain, locale-sensitive String comparison.
javac compiler
may implement the operator with StringBuffer, StringBuilder,
or java.lang.invoke.StringConcatFactory depending on the JDK version. The
implementation of string conversion is typically through the method toString,
defined by Object and inherited by all classes in Java.addAll in interface Collection<E>addAll in interface Set<E>addAll in class AbstractCollection<E>c - collection containing elements to be added to this settrue if this set changed as a result of the callClassCastException - if the elements provided cannot be compared
with the elements currently in the setNullPointerException - 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 elementsE - the List's element typee1 - the first elemente2 - the second elementList containing the specified elementsNullPointerException - if an element is nulle to this set if
the set contains no element e2 such that
Objects.equals(e, e2).
If this set already contains the element, the call leaves the set
unchanged and returns false.e to this set if
the set contains no element e2 such that
Objects.equals(e, e2).
If this set already contains the element, the call leaves the set
unchanged and returns false.add in interface Collection<E>add in interface Set<E>add in class AbstractCollection<E>e - element to be added to this settrue if this set did not already contain the specified
elementClassCastException - if the specified object cannot be compared
with the elements currently in this setNullPointerException - if the specified element is null
and this set uses natural ordering, or its comparator
does not permit null elements