You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Avinandan Bose edited this page Jan 26, 2023
·
2 revisions
Java Collection Framework and Java-Set
This is all about Java Collection.
java.util →Package contains the collection classes let us to group elements in various ways . The Collection Classes also define several methods that provide easier way of working with items . These classes are important , not just for their but because many other Java methods use or return objects of these classes such as the ArrayList and HashMap classes. Collection package added to JSE 1.2 Java SE 8 has significantly increased the power and streamlined the use of collection framework.
(追記) The Collection Framework Interfaces (追記ここまで)
1.Collection
2.Deque
3.List
4.Set
5.Map
6.Sorted Set
7.Sorted Map
8.Queue
9.Navigable Set
(追記) 1. The Collection Interface (追記ここまで)
Collection: It is the top of the collection hierarchy. It supports basic grouping of elements.
The Collection interface is the foundation upon which the Collections Framework is built because it must be implemented by any class that defines a collection.Collection is a generic interface that has this declaration:
interface Collection<E>
Here E specifies the type of objects that the Collection will hold. Consider an example:
Collection<String> co
The above example can be a List, a Set, or another kind of Collection.
Collection: It is the top of the collection hierarchy. It supports basic grouping of elements.Set: It extends Collection to implement sets, in which all elements must be unique.SortedSet: It extends Set to implement a sorted set.HashSet: It extends Set to implement a hash set.LinkedListSet: It extends HashSet to implement a Linked List Set.NavigableSet: It extends SortedSet to implement a Navigable Set.Tree Set: It extends NavigableSet to implement a Tree Set.
That is we can create an instance of TreeSet, HashSet,through the help of Set Interface.:HashSet:
___________→It implements Set Interface.→ Every elements entered are unique i.e. No duplicates.→ HashSet stores the elements by using a mechanism called hashing.→ HashSet allows null value.→ HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.:TreeSet:
___________→It implements Set Interface.→TreeSet class access and retrieval times are quiet fast.→TreeSet class doesn't allow null element.→TreeSet class maintains ascending order. →TreeSet class contains unique elements only like HashSet.
:HASH CODE OF INTEGERS:
HASH CODE OF 1 → 1HASH CODE OF 2 → 2HASH CODE OF 3 → 3......etc.:HASH CODE OF STRINGS:
HASH CODE OF A → 65 //ASCII CODEHASH CODE OF B → 66 //ASCII CODEHASH CODE OF C → 67 //ASCII CODE......etc.
Adds the specified element to this set if it is not already present. More formally, adds the specified element 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.
Removes the specified element from this set if it is present. More formally, removes an element e such that Objects.equals(o, e), if this set contains such an element. Returns true if this set contained the element.
Iterator: It iterates over the elements in the set. The elements are returned in no particular order.Note: The double colon (::) operator, also known as method reference operator.→Double Colon Operator is used to call a method,by referring to it with the help of its class directly.
Performs the given action for each remaining element,until all elements have been processed orthe action throws an exception. Actions are performed,in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.
Removes from the underlying collection the last element,returned by this iterator (optional operation).This method can be called only once per call to next.
Adds all of the elements in the specified collection to this ,set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation,effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is undefined,if the specified collection is modified while the operation is in progress.
Retains only the elements in this collection that are contained,in the specified collection (optional operation)[Intersection]. In other words, removes from this collection all of its elements that are not ,contained in the specified collection.
Returns a Spliterator over the elements in this set.Creates a late-binding and fail-fast Spliterator,over the elements in this set.A late-binding Spliterator,binds to the source of elements means HashSet,at the point of first traversal, first split,or first query for estimated size, rather than at the time the Spliterator is created.
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains,an element e such that Objects.equals(o, e).
From: java.util.AbstractSetDef: Removes from this set all of its elements ,that are contained in the specified collection (optional operation). 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.This implementation determines which is the smaller of this set and the specified collection, by invoking the size method on each. If this set has fewer elements, then the implementation ,iterates over this set, checking each element returned by the iterator,in turn to see if it is contained in the specified collection.
From: java.util.CollectionDef: Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or ,by the predicate are relayed to the caller.
From: java.util.CollectionDef: Returns a possibly parallel Stream with this collection as its source. It is allowable for this method to return a sequential stream.
(追記) Note (追記ここまで):Parallel Stream has similar functions like Streams.
From: java.util.CollectionDef: Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.
From: java.util.AbstractSetDef: Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set.
From: java.util.AbstractSetDef: 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 hash code of a null element is defined to be zero.
We can create instance of HashSet from Abstract Set.AbstractSet class in Java is a part of the Java Collection Framework,which implements the Collection interface and extends,the AbstractCollection class. It provides a skeletal implementation,of the Set interface.
We can create instance of HashSet from Abstract Collection.The AbstractCollection class in Java is a part of the ,Java Collection Framework and implements the Collection interface. It is used to implement an unmodifiable collection, for which one needs to only extend this AbstractCollection Class and implement only the iterator and the size methods.
Def: Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface and SortedSet interface. The objects of the TreeSet class are stored in ascending order.
Continuing...: As TreeSet implements Set , Navigable Set and SortedSet interface , hence it uses functions of Set , NavigableSet and SortedSet interface.
It takes Float value in the Function.Returns the least element in this set greater than or equal to the given element, or null if there is no such element. It returns the Ceil value of the Float Value ,entered in the ceiling function.
It takes Float value in the Function.Returns the greatest element in this set less than or equal to the given element, or null if there is no such element. It returns the Floor value of the Float Value ,entered in the Floor function.
It takes Float value in the Function.:Higher:
----------------Higher Func: Returns the greatest element in the Set corresponding to the number set in Higher Function.Where, the number set in the Function must be present in the given set.Set: [50.58 , 20.78, 30.65, 10.78, 50.98, 60.65,30.65]Higher: set.higher(30.65) = 50.58:Lower:
----------------Lower Func: Returns the lowest element in the Set corresponding to the number set in Lower Function.Where, the number set in the Function must be present in the given set.Set: [50.58 , 20.78, 30.65, 10.78, 50.98, 60.65,30.65]Lower: set.lower(30.65) = 20.78
Descending Iterator: Returns an iterator over the elements in this set in descending order.It has all functions like it have in Iterator i.e. CompareTo, Next , hasNext .
First: Returns first (lowest)element in the set.i.e. set = [2,3,4,1,5,6] , then it will return 1.Last: Returns last (highest)element in the set.i.e. set = [2,3,4,1,5,7,6] , then it will return 7.
Poll First: Retrieves and removes the first (lowest) element, or returns null if this set is empty.i.e. set = [2,3,4,1,5,6] , then it will return 1.And set will be : [2,3,4,5,6]Poll Last: Retrieves and removes the last (highest) element, or returns null if this set is empty.i.e. set = [2,3,4,1,5,7,6] , then it will return 7.And set will be : [2,3,4,1,5,6]
Implemented From : java.util.SortedSetIt returns Sub Set i.e. From a Starting Element to the Last Element.i.e. if Set = [1,2,3,4,5,6];And Subset :→ From Element : 2And To Element: 6IT will return set: [3,4,5]
Implemented From : java.util.NavigableSetIt returns Sub Set i.e. From a Starting Element to the Last Element.i.e. if Set = [1,2,3,4,5,6];And Subset :→ From Element : 2 , boolean fromInclusive : trueAnd To Element: 6 , boolean toInclusive : falseIT will return set: [2,3,4,5]Similarly:
Subset :→ From Element : 2 , boolean fromInclusive : falseAnd To Element: 6 , boolean toInclusive : falseIT will return set: [3,4,5]
Implemented From : java.util.SortedSetIt returns Set from a Starting Element set to TailSet function.i.e. if Set = [1,2,3,4,5,6];And tailset :→ From Element : 2IT will return set: [2,3,4,5,6]
Implemented From : java.util.SortedSetIt returns Set upto a Ending Element but not the Ending Element set to HeadSet function.i.e. if Set = [1,2,3,4,5,6];And To Element: 6 ,IT will return set: [1,2,3,4,5]
Implemented From : java.util.NavigableSetIt returns Set from a Starting Element set to TailSet function if Boolean Inclusive set to True,Else returns Set from a Starting Element set to TailSet function except the Starting Element ,if Boolean Inclusive set to False.i.e. if Set = [1,2,3,4,5,6];And tailset :→ From Element : 2And inclusive : trueIT will return set: [2,3,4,5,6]Else:
tailset :→ From Element : 2And inclusive : falseIT will return set: [3,4,5,6]
Implemented From : java.util.NavigableSetIt returns Set upto a Ending Element but not the Ending Element set to HeadSet function,if Boolean Inclusive set to True,Else It returns Set upto a Ending Element with the Ending Element set to HeadSet function,if Boolean Inclusive set to False.i.e. if Set = [1,2,3,4,5,6];And HeadSet :→ To Element : 6And inclusive : TrueIT will return set: [1,2,3,4,5]Else:
tailset :→ To Element : 6And inclusive : falseIT will return set: [1,2,3,4,5,6]
Implemented From : java.util.NavigableSetIt makes the output of Set in Descending Order i.e. From ,Greatest Element to Lowest Element.
Comparator Interface on Tree Set
Comparator helps to find the sorting order used in the TreeSet objects ; for example, with the implementation of the Comparator interface.The methods provided by the interface are:
Methods of the Comparator interface
Method
Does This
int compare(Object obj1,Object obj2)
It compares its two arguments.
boolean equals(Object obj)
It specifies whether another object is equal to this comparator.
This class extends HashSet, but adds no members of its own. LinkedHashSet is an ordered and sorted collection of HashSet. LinkedHashSet maintains the insertion order of the elements.It uses a doubly linked list to maintain the insertion order. LinkedHashSet implement the Set interface like HashSet.
The Sorted Set interface Set extends Set and declares the behavior of a set sorted in ascending order. Sorted Set is a generic interface that has this declaration:
interface SortedSet<E>
Here E specifies the type of objects that the Set will hold.
Interface
Methods
SortedSet
first
last
headSet
tailSet
subSet
About Navigable Set Interface
The NavigableSet interface extends SortedSet and declares the behavior of a collection that supports the retrieval of elements based on the closest match to a given value or values. NavigableSet is a generic interface that has this declaration :
interface NavigableSet<E>
Here E specifies the type of objects that the Set will hold.
Interface
Methods
NavigableSet
ceiling
floor
descendingIterator
descendingSet
headSet
tailSet
subSet
higher
lower
pollFirst
pollLast
(追記) Note: (追記ここまで) Collection , Set, SortedSet, Navigable Set are all interfaces and we cannot create their objects due their abstract nature.
About AbstractCollection
The AbstractCollection class is an Abstract Class provides an implementation of the Collection interface. It is used to implement an unmodifiable collection, for which one needs to only extend this AbstractCollection Class and implement only the iterator and the size methods.
abstract class AbstractCollection<E> extends Object implements Collection<E>
where E is the type of elements.
Abstract Class
Methods
AbstractCollection
Add
AddAll
Clear
Contains
ContainsAll
isEmpty
Iterator
Remove
Size
toArray
toString
About AbstractSet
AbstractSet is an Abstract class in Java is a part of the Java Collection Framework which implements the Collection interface and extends the AbstractCollection class. It provides a skeletal implementation of the Set interface.
abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>
Creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type,that are not contained in the specified set.
Creates an empty enum set with the specified element type.
CopyOnWriteArraySet
To use this class, we need to import it from java.util.concurrent package.
CopyOnWriteArraySet is a member of the Java Collections Framework.
It is a Set that uses an internal CopyOnWriteArrayList for all of its operations.
It was introduced in JDK 1.5, we can say that it is a thread-safe version of Set.
That is Multiple Threads are able to perform update operations simultaneously but for every update operation, a separate cloned copy is created.
While one thread iterating the Set, other threads can perform updation.
Iterators returned are fail-safe.
It is synchronized.
An Iterator of CopyOnWriteArraySet class can perform only read-only and should not perform the deletion, otherwise, we will get Run-time exception UnsupportedOperationException.
It is slower compared to HashSet since it is synchronized.
The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework .
The ConcurrentSkipListSet class in Java implements the Collection interface and the AbstractSet class .
The ConcurrentSkipListSet class is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.
The elements of the ConcurrentSkipListSet are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
The ConcurrentSkipListSet class implements Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet interfaces.
The ConcurrentSkipListSet does not allow null elements, because null arguments and return values cannot be reliably distinguished from the absence of elements.