Class LinkedHashSet is the Collections Framework's realization of the concept of the SequencedSet. It can be used when the order
of the elements in the set should be predictable, since this guarantee is not provided by the HashSet. Elements
in a LinkedHashSet are stored and iterable in the order they were added to the set.
package collections.sets;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.SequencedCollection;
import java.util.SequencedSet;
public class UsingLinkedHashSet {
public static void main(String[] args) {
String[] letters = {"A", "C", "B", "A"};
LinkedHashSet<String> set = new LinkedHashSet<>(Arrays.asList()); // [A,C,B]
set.add("D"); // [A,C,B,D]
set.add("C"); // [A,C,B,D]
// Reversed Views
SequencedSet<String> reversed = set.reversed(); // [D,B,C,A]
set.remove("D");
System.out.println(reversed); // [B,C,A]
// Reinsertion
<String> sequence = set;
sequence.addFirst("D"); // [D,A,C,B]
sequence.addFirst("A"); // [A,D,C,B]
sequence.addLast("C"); // [A,D,B,C]
}
}
Adding elements adds them at the end of the sequence. Attempting to re-insert duplicates has no effect.
Adding elements adds them at the end of the sequence. Attempting to re-insert duplicates has no effect.
LinkedHashSet implements interface SequencedSet, which defines the method reversed(). This method
returns a SequencedSet that is a of the original set with its elements in reverse order.
As opposed to method add, methods addFirst and addLast have an effect when supplied with an element that is
already in the set: it re-inserts it in first position or last position, respectively.
As opposed to method add, methods addFirst and addLast have an effect when supplied with an element that is
already in the set: it re-inserts it in first position or last position, respectively.
The LinkedHashSet preserves encounter order. When iterating over
the set, the set's elements will be returned in the order they
were added to the set. Duplicates are not reinserted.
The LinkedHashSet preserves encounter order. When iterating over
the set, the set's elements will be returned in the order they
were added to the set. Duplicates are not reinserted.
Hash table and linked list implementation of the Set interface,
with well-defined encounter 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 encounter order (iteration
order), which is the order in which elements were inserted into the set
(insertion-order). The least recently inserted element (the eldest) is
first, and the youngest element is last. Note that encounter order is not affected
if an element is re-inserted into the set with the add method.
(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.) The reverse-ordered view of this set is in the opposite order, with
the youngest element appearing first and the eldest element appearing last. The encounter
order of elements already in the set can be changed by using the
addFirst and addLast methods.
Hash table and linked list implementation of the Set interface,
with well-defined encounter 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 encounter order (iteration
order), which is the order in which elements were inserted into the set
(insertion-order). The least recently inserted element (the eldest) is
first, and the youngest element is last. Note that encounter order is not affected
if an element is re-inserted into the set with the add method.
(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.) The reverse-ordered view of this set is in the opposite order, with
the youngest element appearing first and the eldest element appearing last. The encounter
order of elements already in the set can be changed by using the
addFirst and addLast methods.
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<String> s) {
Set<String> 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 and SequencedSet
operations, and it 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.
c - the collection whose elements are to be placed into
this setNullPointerException - if the specified collection is nullA LinkedHashSet implements the SequencedCollection
interface, which defines methods such as addFirst/addLast and removeFirst/removeLast.
A LinkedHashSet implements the SequencedCollection
interface, which defines methods such as addFirst/addLast and removeFirst/removeLast.
(Note that this definition does not imply anything about physical positioning of elements, such as their locations in a computer's memory.)
Several methods inherited from the Collection interface are required to operate
on elements according to this collection's encounter order. For instance, the
iterator method provides elements starting from the first element,
proceeding through successive elements, until the last element. Other methods that are
required to operate on elements in encounter order include the following:
forEach, parallelStream,
spliterator, stream,
and all overloads of the toArray method.
This interface provides methods to add, retrieve, and remove elements at either end of the collection.
This interface also defines the reversed method, which provides
a reverse-ordered view of this collection.
In the reverse-ordered view, the concepts of first and last are inverted, as are
the concepts of successor and predecessor. The first element of this collection is
the last element of the reverse-ordered view, and vice-versa. The successor of some
element in this collection is its predecessor in the reversed view, and vice-versa. All
methods that respect the encounter order of the collection operate as if the encounter order
is inverted. For instance, the Collection.iterator() method of the reversed view reports the
elements in order from the last element of this collection to the first. The availability of
the reversed method, and its impact on the ordering semantics of all applicable
methods, allow convenient iteration, searching, copying, and streaming of the elements of
this collection in either forward order or reverse order.
This class is a member of the Java Collections Framework.
equals and hashCode
methods, because requirements imposed by sub-interfaces List and SequencedSet
(which inherits requirements from Set) would be in conflict. See the specifications for
Collection.equals and Collection.hashCode
for further information.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]
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]
String 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.The methods in this class all throw a NullPointerException,
if the specified array reference is null, except where noted.
The documentation for the methods contained in this class includes
brief descriptions of the implementations. Such descriptions should
be regarded as implementation notes, rather than parts of the
specification. Implementors should feel free to substitute other
algorithms, so long as the specification itself is adhered to. (For
example, the algorithm used by sort(Object[]) does not have to be
a MergeSort, but it does have to be stable.)
This class is a member of the Java Collections Framework.
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 Object to be printed.UnsupportedOperationException.e - the element to be addedNullPointerException - if the specified element is null and this
collection does not permit null elementsUnsupportedOperationException - if this collection implementation
does not support this operationUnsupportedOperationException.e - the element to be added.NullPointerException - if the specified element is null and this
collection does not permit null elementsUnsupportedOperationException - if this collection implementation
does not support this operationSerializable and implements RandomAccess.
Serializable and implements RandomAccess.
The returned list implements the optional Collection methods, except
those that would change the size of the returned list. Those methods leave
the list unchanged and throw UnsupportedOperationException.
If the specified array's actual component type differs from the type
parameter T, this can result in operations on the returned list throwing an
ArrayStoreException.
Collection.toArray().
This method provides a way to wrap an existing array:
Integer[] numbers = ...
...
List<Integer> values = Arrays.asList(numbers);
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
The list returned by this method is modifiable.
To create an unmodifiable list, use
Collections.unmodifiableList
or Unmodifiable Lists.
T - the class of the objects in the arraya - the array by which the list will be backedNullPointerException - if the specified array is nullHash table and linked list implementation of the Set interface,
with well-defined encounter 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 encounter order (iteration
order), which is the order in which elements were inserted into the set
(insertion-order). The least recently inserted element (the eldest) is
first, and the youngest element is last. Note that encounter order is not affected
if an element is re-inserted into the set with the add method.
(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.) The reverse-ordered view of this set is in the opposite order, with
the youngest element appearing first and the eldest element appearing last. The encounter
order of elements already in the set can be changed by using the
addFirst and addLast methods.
Hash table and linked list implementation of the Set interface,
with well-defined encounter 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 encounter order (iteration
order), which is the order in which elements were inserted into the set
(insertion-order). The least recently inserted element (the eldest) is
first, and the youngest element is last. Note that encounter order is not affected
if an element is re-inserted into the set with the add method.
(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.) The reverse-ordered view of this set is in the opposite order, with
the youngest element appearing first and the eldest element appearing last. The encounter
order of elements already in the set can be changed by using the
addFirst and addLast methods.
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<String> s) {
Set<String> 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 and SequencedSet
operations, and it 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.
e to this set if
this 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
this 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
elementModifications to the reversed view are permitted and will be propagated to this set. In addition, modifications to this set will be visible in the reversed view.
reversed in interface SequencedCollection<E>reversed in interface SequencedSet<E>SequencedSetSequencedCollection and a Set. As such,
it can be thought of either as a Set that also has a well-defined
encounter order, or as a
SequencedCollection that also has unique elements.
SequencedCollection and a Set. As such,
it can be thought of either as a Set that also has a well-defined
encounter order, or as a
SequencedCollection that also has unique elements.
This interface has the same requirements on the equals and hashCode
methods as defined by Set.equals and Set.hashCode.
Thus, a Set and a SequencedSet will compare equals if and only
if they have equal elements, irrespective of ordering.
SequencedSet defines the reversed() method, which provides a
reverse-ordered view of this set. The only difference
from the SequencedCollection.reversed method is
that the return type of SequencedSet.reversed is SequencedSet.
This class is a member of the Java Collections Framework.
e such that
Objects.equals(o, 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.)e such that
Objects.equals(o, 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.)remove in interface Collection<E>remove in interface Set<E>remove in class AbstractCollection<E>o - object to be removed from this set, if presenttrue if the set contained the specified elementSystem 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.