Collection-1
Collection-1
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
collection.
E> c)
collection.
E> filter)
collection.
the collection.
contains(Object element)
10 public boolean It is used to search the specified collection in
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
specified array.
element)
collection.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction
only.
There are only three methods in the Iterator interface. They are:
N Method Description
o.
1 public boolean It returns true if the iterator has more elements otherwise
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
package com.flm;
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();// Creating arraylist
list.add("Ravi");// Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface
so we can use all the methods of the List interface here. The ArrayList maintains the
insertion order internally.
○ In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.
○ We can not create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:
○ Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list
Constructors of ArrayList
onstructor Description
ayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the
collection c.
ayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList
Method Description
void add(int index, E It is used to insert the specified element at the specified
boolean add(E e) It is used to append the specified element at the end of a list.
addAll(Collection<? collection to the end of this list, in the order that they are
extends E> c)
void clear() It is used to remove all of the elements from this list.
void It is used to enhance the capacity of an ArrayList instance.
ensureCapacity(int
requiredCapacity)
E get(int index) It is used to fetch the element from the particular position of
the list.
Iterator()
listIterator()
int It is used to return the index in this list of the last occurrence
lastIndexOf(Object of the specified element, or -1 if the list does not contain this
o) element.
contains(Object o)
int indexOf(Object o) It is used to return the index in this list of the first occurrence
element.
remove(Object o) element.
boolean It is used to remove all the elements from the list.
removeAll(Collection
<?> c)
boolean It is used to remove all the elements from the list that satisfies
protected void It is used to remove all the elements lies within the given
removeRange(int range.
fromIndex, int
toIndex)
void It is used to replace all the elements from the list with the
rator<E> operator)
void It is used to retain all the elements in the list that are present
?> c)
E set(int index, E It is used to replace the specified element in the list, present at
void It is used to sort the elements of the list on the basis of the
super E> c)
spliterator()
List<E> subList(int It is used to fetch all the elements that lies within the given
toIndex)
int size() It is used to return the number of elements present in the list.
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it
is type-safe, so typecasting is not required at runtime.
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of object in it. If you try to add another type of object, it gives a
compile-time error.
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
FileName: ArrayListExample3.java
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Grapes");
for(String fruit:list)
System.out.println(fruit);
The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
Collections.sort(list1);
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
Collections.sort(list2);
for(Integer number:list2)
System.out.println(number);
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
class Student{
int rollno;
String name;
int age;
this.rollno=rollno;
this.name=name;
this.age=age;
—--------
import java.util.*;
class ArrayList5{
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
Size and capacity of an array list are the two terms that beginners find confusing. Let's
understand it in this section with the help of some examples. Consider the following code
snippet.
FileName: SizeCapacity.java
import java.util.*;
Output:
Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.
import java.util.*;
Output:
Explanation: We see that the size is still 0, and the reason behind this is the number 10
represents the capacity not the size. In fact, the size represents the total number of
elements present in the array. As we have not added any element, therefore, the size of the
array list is zero in both programs.
Capacity represents the total number of elements the array list can contain. Therefore, the
capacity of an array list is always greater than or equal to the size of the array list. When we
add an element to the array list, it checks whether the size of the array list has become equal
to the capacity or not. If yes, then the capacity of the array list increases. So, in the above
example, the capacity will be 10 till 10 elements are added to the list. When we add the 11th
element, the capacity increases. Note that in both examples, the capacity of the array list is
10. In the first case, the capacity is 10 because the default capacity of the array list is 10. In
the second case, we have explicitly mentioned that the capacity of the array list is 10.
LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
As shown in the above diagram, Java LinkedList class extends AbstractSequentialList class
and implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
Constructor Description
tion<? extends specified collection, in the order, they are returned by the
Method Description
boolean add(E e) It is used to append the specified element to the end of a list.
void add(int index, It is used to insert the specified element at the specified
addAll(Collection<? collection to the end of this list, in the order that they are
addAll(Collection<? collection to the end of this list, in the order that they are
boolean addAll(int It is used to append all the elements in the specified collection,
extends E> c)
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
contains(Object o)
E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.
int indexOf(Object It is used to return the index in a list of the first occurrence of
element.
lastIndexOf(Object the specified element, or -1 if the list does not contain any
o) element.
index)
boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E It inserts the specified element at the front of a list.
e)
e)
empty.
empty.
if a list is empty.
list.
removeFirstOccurre element in a list (when traversing the list from head to tail).
nce(Object o)
nce(Object o)
E set(int index, E It replaces the element at the specified position in a list with
Object[] toArray() It is used to return an array containing all the elements in a list
<T> T[] toArray(T[] It returns an array containing all the elements in the proper
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
However, there are many differences between the ArrayList and LinkedList classes that are
given below.
ArrayList LinkedList
because it internally uses an array. If any faster than ArrayList because it uses
element is removed from the array, all the a doubly linked list, so no bit shifting
3) An ArrayList class can act as a list only LinkedList class can act as a list and
5) The memory location for the elements of The location for the elements of a
LinkedList is initialized.
Points to Remember
The following are some important points to remember regarding an ArrayList and
LinkedList.
○ When the rate of addition or removal rate is more than the read scenarios, then go for
the LinkedList. On the other hand, when the frequency of the read scenarios is more
than the addition or removal rate, then ArrayList takes precedence over LinkedList.
Method Description
void add(E e) This method inserts the specified element into the list.
boolean This method returns true if the list iterator has more elements while
E next() This method returns the next element in the list and advances the
cursor position.
int This method returns the index of the element that would be returned
boolean This method returns true if this list iterator has more elements while
E previous() This method returns the previous element in the list and moves the
E This method returns the index of the element that would be returned
x()
void This method removes the last element from the list that was returned
void set(E e) This method replaces the last element returned by next() or previous()
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
○ HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
A list can contain duplicate elements whereas Set contains unique elements only.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet
4) boolea contains( It is used to return true if this set contains the specified
n Object o) element.
r<E> set.
7) boolea remove(O It is used to remove the specified element from this set if
n bject o) it is present.
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.
import java.util.*;
class HashSet1{
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
System.out.println(i.next());
}
Java LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.
○ Java LinkedHashSet class provides all optional set operations and permits null
elements.
The LinkedHashSet class extends the HashSet class, which implements the Set interface.
The Set interface inherits Collection and Iterable interfaces in hierarchical order.
Constructor Description
HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.
LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the
LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also
capacity, float fillRatio) called load capacity) of the hash set from its argument.
Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the
elements iterate in insertion order.
FileName: LinkedHashSet1.java
import java.util.*;
class LinkedHashSet1{
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
System.out.println(i.next());
TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet
class are stored in ascending order.
○ Java TreeSet class access and retrieval times are quiet fast.
○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.
As already mentioned above, the TreeSet class is not synchronized. It means if more than
one thread concurrently accesses a tree set, and one of the accessing threads modify it,
then the synchronization must be done manually. It is usually done by doing some object
synchronization that encapsulates the set. However, in the case where no such object is
found, then the set must be wrapped with the help of the Collections.synchronizedSet()
method. It is advised to use the method during creation time in order to avoid the
unsynchronized access of the set. The following code snippet shows the same.
Constructor Description
TreeSet(Collection<? It is used to build a new tree set that contains the elements of
s) given SortedSet.
Methods of Java TreeSet Class
Method Description
in order.
order.
is no such element.
SortedSet headSet(E toElement) It returns the group of elements that are less
NavigableSet headSet(E toElement, It returns the group of elements that are less
element.
such element.
order.
such element.
E pollFirst() It is used to retrieve and remove the lowest(first)
element.
element.
NavigableSet subSet(E fromElement, It returns a set of elements that lie between the
boolean toInclusive)
SortedSet subSet(E fromElement, E It returns a set of elements that lie between the
excludes toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than
element.
element.
set.
instance.
FileName: TreeSet1.java
import java.util.*;
class TreeSet1{
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
—-----
import java.util.*;
class TreeSet3{
set.add(24);
set.add(66);
set.add(12);
set.add(15);