Class ListSet<E>
- java.lang.Object
-
- java.util.AbstractCollection<E>
-
- java.util.AbstractSet<E>
-
- eu.simuline.util.ListSet<E>
-
- Type Parameters:
E- The type of the entries.
- All Implemented Interfaces:
Iterable<E>,Collection<E>,Set<E>,SortedSet<E>
public final class ListSet<E> extends AbstractSet<E> implements SortedSet<E>
This class implements the Set interface, backed by ajava.util.ArrayList. The iteration order of the set is the iteration order of the underlying ArrayList. This class permits the null element.The size, isEmpty, and iterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking).
Each ListSet instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the set size. As elements are added an ListSet, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
Note that this implementation is not synchronized. If multiple threads access a 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 ListSet instance:
Set s = Collections.synchronizedSet(new ListSet(...));
The iterators returned by this class's iterator method are fail-fast: if the set ismodified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws 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.
- Version:
- 1.0
- Author:
- Ernst Reissner
- See Also:
Collection,List,ArrayList.add(E, java.lang.Object[], int),SortedSet,HashSet,TreeSet,AbstractSet,Collections
-
-
Field Summary
Fields Modifier and Type Field Description private Comparator<? super E>innerCmpIfouterCmpis notnull, the two comparators coincide.private List<E>listContains the elements of this set.private Comparator<? super E>outerCmpThe comparator initialized in the constructor and returned bycomparator().
-
Constructor Summary
Constructors Modifier Constructor Description ListSet()Constructs a new, empty set, sorted according to the natural ordering of its elements.ListSet(Collection<? extends E> coll)Creates a new set containing the elements of the specified collection in the natural ordering.ListSet(Comparator<? super E> cmp)Constructs a new, empty set, sorted according to the specified comparatorcmp.privateListSet(List<E> list, Comparator<? super E> cmp)Creates a newListSetwith elements given bylistand ordering given bycmp.ListSet(SortedSet<E> sortedSet)Constructs a new set containing the same elements and using the same ordering as thesortedSet.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanadd(E obj)Adds the specified element to this set if it is not already present.booleanaddAll(Collection<? extends E> coll)Adds all of the elements in the specified collection to this set if they're not already present.private booleanaddList(List<E> list1, List<E> list2)Mergeslist2intolist1and returns whetherl1had been modified.voidclear()Removes all of the elements from this set.Comparator<? super E>comparator()booleancontains(Object obj)Returnstrueif this set contains the specified element.booleancontainsAll(Collection<?> coll)Returnstrueif this set contains all of the elements of the specified collection.booleanequals(Object obj)**** ask at oracle whether for sorted sets equality should include ordering. **** Compares the specified object with this set for equality.Efirst()List<E>getList()Returns a list backing this set, so changes in the returned list are reflected in this set, and vice-versa.inthashCode()Returns the hash code value for this set.SortedSet<E>headSet(E toObj)booleanisEmpty()Returnstrueif this set contains no elements.private booleanisSortedWithSameComparator(Collection<?> coll)Returns whether this set has the same comparator as the collection given.Iterator<E>iterator()Returns an iterator over the elements in this set.Elast()ListIterator<E>listIterator()Returns an iterator over the elements in this set.static voidmain(String[] args)(package private) intobj2idx(E obj)booleanremove(Object obj)Removes the specified element from this set if it is present.booleanremoveAll(Collection<?> coll)Removes from this set all of its elements that are contained in the specified collection.booleanretainAll(Collection<?> coll)Retains only the elements in this set that are contained in the specified collection.intsize()Returns the number of elements in this set (its cardinality).static <E> ListSet<E>sortedAsAdded()Creates a newListSetwith ordering as added in ascending ordering.static <E> ListSet<E>sortedAsListed(List<E> list)Returns anListSetwith elements and ordering given bylistas described inComparators.getAsListed(List).ListSet<E>subSet(E fromObj, E toObj)(package private) ListSet<E>subSetIdx(int fromIdx, int toIdx)SortedSet<E>tailSet(E fromObj)Object[]toArray()Returns an array containing all of the elements in this set; the order is as in the backing listlist.<T> T[]toArray(T[] arr)Returns an array containing all of the elements in this set whose runtime type is that of the specified array; the order is as in the backing listlist.StringtoString()Returns a string representation of this set.-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface java.util.Collection
parallelStream, removeIf, stream, toArray
-
Methods inherited from interface java.util.SortedSet
spliterator
-
-
-
-
Field Detail
-
list
private final List<E> list
Contains the elements of this set. By contract,list.get(a).equals(list.get(b))impliesa == b.
-
outerCmp
private final Comparator<? super E> outerCmp
The comparator initialized in the constructor and returned bycomparator(). This may well benulland is nowhere used directly.
-
innerCmp
private final Comparator<? super E> innerCmp
IfouterCmpis notnull, the two comparators coincide. Otherwise this comparator reflects the natural ordering and throws aClassCastExceptionif feeded with no appropriateComparable.
-
-
Constructor Detail
-
ListSet
private ListSet(List<E> list, Comparator<? super E> cmp)
Creates a newListSetwith elements given bylistand ordering given bycmp. If the latter isnullthen the type parameter oflistmust be aComparable. andlistmust This is inspired by a constructor of TreeSet.- Parameters:
list- the list wrapped by this set. It must be ordered ascending according tocmpif this is non-null, else asComparables. It is desireable thatlistcontains each element once only.cmp- A comparator ornull.
-
ListSet
public ListSet(SortedSet<E> sortedSet)
Constructs a new set containing the same elements and using the same ordering as thesortedSet.- Parameters:
sortedSet- sorted set whose elements will comprise the new set- Throws:
NullPointerException- if the specified sorted set isnull.
-
ListSet
public ListSet(Collection<? extends E> coll)
Creates a new set containing the elements of the specified collection in the natural ordering. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable:e1.compareTo(e2)must not throw a ClassCastException for any elementse1ande2in the set.The backing ArrayList instance
listhas an initial capacity of 110% the size of the specified collection.- Parameters:
coll- the collection whose elements are to be placed into this set.- Throws:
ClassCastException- if the elements in c are not Comparable, or are not mutually comparable.NullPointerException- if the specified collection isnull.
-
ListSet
public ListSet(Comparator<? super E> cmp)
Constructs a new, empty set, sorted according to the specified comparatorcmp. Forcmp==nulla comparator defining the natural ordering is assumed.All elements inserted into the set must be mutually comparable by the specified comparator:
cmp.compare(e1, e2)must not throw a ClassCastException for any elementse1ande2in the set. If the user attempts to add an element to the set that violates this constraint, the add call will throw aClassCastException.Implementational note: Whereas
outerCmpis initialized withcmpwhether it isnullor not,innerCmpis initialized withcmponly if this is notnull. Otherwise, it is initialized with a comparator defining the natural ordering.- Parameters:
cmp- the comparator that will be used to order this set. If null, the natural ordering of the elements will be used.
-
ListSet
public ListSet()
Constructs a new, empty set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable:e1.compareTo(e2)must not throw a ClassCastException for any elementse1ande2in 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 aClassCastException. For a generalization to a given comparator seeListSet(Comparator).
-
-
Method Detail
-
sortedAsAdded
public static <E> ListSet<E> sortedAsAdded()
Creates a newListSetwith ordering as added in ascending ordering.
-
sortedAsListed
public static <E> ListSet<E> sortedAsListed(List<E> list)
Returns anListSetwith elements and ordering given bylistas described inComparators.getAsListed(List). If an element is added tolist, the ordering is as added at the end oflist. CAUTION: The list backs this set: changes in the list affect this set and the other way round. Changing the list also changes the ordering.- Throws:
NullPointerException- iflistisnull.
-
getList
public List<E> getList()
Returns a list backing this set, so changes in the returned list are reflected in this set, and vice-versa.
-
size
public int size()
Returns the number of elements in this set (its cardinality). If thisset contains more thanInteger.MAX_VALUEelements, returnsInteger.MAX_VALUE.- Specified by:
sizein interfaceCollection<E>- Specified by:
sizein interfaceSet<E>- Specified by:
sizein classAbstractCollection<E>- Returns:
- the number of elements in this set (its cardinality).
-
isEmpty
public boolean isEmpty()
Returnstrueif this set contains no elements.- Specified by:
isEmptyin interfaceCollection<E>- Specified by:
isEmptyin interfaceSet<E>- Overrides:
isEmptyin classAbstractCollection<E>- Returns:
trueif this set contains no elements.
-
contains
public boolean contains(Object obj)
Returnstrueif this set contains the specified element. More formally, returnstrueif and only if this set contains an elementesuch that(obj==null ? e==null : obj.equals(e)).- Specified by:
containsin interfaceCollection<E>- Specified by:
containsin interfaceSet<E>- Overrides:
containsin classAbstractCollection<E>- Parameters:
obj- obj is some object that may be in this collection.- Returns:
trueif this set contains the specified element.
-
iterator
public Iterator<E> iterator()
Returns an iterator over the elements in this set. The elements are returned in the particular order in which they are stored inlist.
-
listIterator
public ListIterator<E> listIterator()
Returns an iterator over the elements in this set. The elements are returned in the particular order in which they are stored inlist.- Returns:
- an iterator over the elements in this set.
-
toArray
public Object[] toArray()
Returns an array containing all of the elements in this set; the order is as in the backing listlist. Obeys the general contract of theCollection.toArraymethod.- Specified by:
toArrayin interfaceCollection<E>- Specified by:
toArrayin interfaceSet<E>- Overrides:
toArrayin classAbstractCollection<E>- Returns:
- an array containing all of the elements in this set.
-
toArray
public <T> T[] toArray(T[] arr)
Returns an array containing all of the elements in this set whose runtime type is that of the specified array; the order is as in the backing listlist. Obeys the general contract of theCollection.toArray(Object[])method.- Specified by:
toArrayin interfaceCollection<E>- Specified by:
toArrayin interfaceSet<E>- Overrides:
toArrayin classAbstractCollection<E>- Parameters:
arr- the array into which the elements of this set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.- Returns:
- an array containing the elements of this set.
- Throws:
ArrayStoreException- the runtime type of a is not a supertype of the runtime type of every element in this set.
-
add
public boolean add(E obj)
Adds the specified element to this set if it is not already present. More formally, adds the specified element,o, to this set if this set contains no elementesuch that(o==null ? e==null : o.equals(e)). If this set already contains the specified element, the call leaves this set unchanged and returnsfalse. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.Note that also
nullmay be added to this set, but only if it is not already present, this changes this set.- Specified by:
addin interfaceCollection<E>- Specified by:
addin interfaceSet<E>- Overrides:
addin classAbstractCollection<E>- Parameters:
obj- element to be added to this set.- Returns:
trueif this set did not already contain the specified element.
-
remove
public boolean remove(Object obj)
Removes the specified element from this set if it is present. More formally, removes an elementesuch that(o==null ? e==null : o.equals(e)), if the set contains such an element. Returnstrueif the set contained the specified element (or equivalently, if the set changed as a result of the call). (The set will not contain the specified element once the call returns.)- Specified by:
removein interfaceCollection<E>- Specified by:
removein interfaceSet<E>- Overrides:
removein classAbstractCollection<E>- Parameters:
obj- object to be removed from this set, if present.- Returns:
trueif the set contained the specified element.
-
containsAll
public boolean containsAll(Collection<?> coll)
Returnstrueif this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returnstrueif it is a subset of this set.- Specified by:
containsAllin interfaceCollection<E>- Specified by:
containsAllin interfaceSet<E>- Overrides:
containsAllin classAbstractCollection<E>- Parameters:
coll- collection to be checked for containment in this set.- Returns:
trueif this set contains all of the elements of the specified collection.
-
isSortedWithSameComparator
private boolean isSortedWithSameComparator(Collection<?> coll)
Returns whether this set has the same comparator as the collection given.- Parameters:
coll- a collection which may be aSortedSetor not.- Returns:
trueifcis a sorted set and ifc.comparatoryields the same result:-
Either they coincide as pointers,
including the case that both are
null -
or at least this comparator is not
nulland equals the other one. This case implies that neither arenull.
-
Either they coincide as pointers,
including the case that both are
-
addAll
public boolean addAll(Collection<? extends E> coll)
Adds all of the elements in the specified collection to this set if they're not already present. If the specified collection is also a set, theaddAlloperation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress.- Specified by:
addAllin interfaceCollection<E>- Specified by:
addAllin interfaceSet<E>- Overrides:
addAllin classAbstractCollection<E>- Parameters:
coll- collection whose elements are to be added to this set.- Returns:
trueif this set changed as a result of the call.- See Also:
add(E)
-
addList
private boolean addList(List<E> list1, List<E> list2)
Mergeslist2intolist1and returns whetherl1had been modified. At the end,list2is not modified andlist1is ordered again.
-
retainAll
public boolean retainAll(Collection<?> coll)
Retains only the elements in this set that are contained in the specified collection. In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.- Specified by:
retainAllin interfaceCollection<E>- Specified by:
retainAllin interfaceSet<E>- Overrides:
retainAllin classAbstractCollection<E>- Parameters:
coll- collection that defines which elements this set will retain.- Returns:
trueif this collection changed as a result of the call.- See Also:
remove(java.lang.Object)
-
removeAll
public boolean removeAll(Collection<?> coll)
Removes from this set all of its elements that are contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.- Specified by:
removeAllin interfaceCollection<E>- Specified by:
removeAllin interfaceSet<E>- Overrides:
removeAllin classAbstractSet<E>- Parameters:
coll- collection that defines which elements will be removed from this set.- Returns:
trueif this set changed as a result of the call.- See Also:
remove(java.lang.Object)
-
clear
public void clear()
Removes all of the elements from this set. This set will be empty after this call returns.- Specified by:
clearin interfaceCollection<E>- Specified by:
clearin interfaceSet<E>- Overrides:
clearin classAbstractCollection<E>
-
comparator
public Comparator<? super E> comparator()
- Specified by:
comparatorin interfaceSortedSet<E>
-
obj2idx
int obj2idx(E obj)
-
equals
public boolean equals(Object obj)
**** ask at oracle whether for sorted sets equality should include ordering. **** Compares the specified object with this set for equality. Returnstrueif the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.- Specified by:
equalsin interfaceCollection<E>- Specified by:
equalsin interfaceSet<E>- Overrides:
equalsin classAbstractSet<E>- Parameters:
obj- Object to be compared for equality with this set.- Returns:
trueif the specified Object is equal to this set.
-
toString
public String toString()
Returns a string representation of this set.- Overrides:
toStringin classAbstractCollection<E>- Returns:
- a comma separated list of
String-representations of the elements of this list enclosed in triangle brackets.
-
hashCode
public int hashCode()
Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hashcode of anullelement is defined to be zero. This ensures thats1.equals(s2)implies thats1.hashCode()==s2.hashCode()for any two setss1ands2, as required by the general contract of theObject.hashCodemethod.- Specified by:
hashCodein interfaceCollection<E>- Specified by:
hashCodein interfaceSet<E>- Overrides:
hashCodein classAbstractSet<E>- Returns:
- the hash code value for this set.
- See Also:
Object.hashCode(),Object.equals(Object),Set.equals(Object)
-
main
public static void main(String[] args)
-
-