https://github.com/avinandanbose/javacollection_list_vector
Here is all about java List of Collection Package
https://github.com/avinandanbose/javacollection_list_vector
Last synced: 4 months ago
JSON representation
Here is all about java List of Collection Package
- Host: GitHub
- URL: https://github.com/avinandanbose/javacollection_list_vector
- Owner: AvinandanBose
- License: mit
- Created: 2023-02-27T10:21:28.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-03-27T19:25:11.000Z (over 2 years ago)
- Last Synced: 2025-01-26T17:11:23.085Z (9 months ago)
- Language: Java
- Size: 277 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Java Collection-List
The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or accessed by
their position in the list, using a zero-based index. A list may contain duplicate elements. List is a generic interface that has this declaration:
```
public interface List extends Collection```
Here, E specifies the type of objects that the list will hold.
List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface.
1.Collection: → It is the top of the collection hierarchy.It supports basic grouping of elements.
2.AbstractCollection: → It implements the Collection interface.
3.List: → It extends Collection to implement lists of objects.
4.AbstractList: → It extends the AbstractCollection and implements the List interface.
5.AbstractSequentialList: → It extends the AbstractList into a sequential(not random access)list.
6.LinkedList: → It extends the AbstractSequentialList into a linked list, where each element knows where the next element is.
7.ArrayList: → It implements a dynamic(resizable) array.
AbstractList
```mermaid
sequenceDiagram
java.util.Collection->>java.util.AbstractCollection:implements
java.lang.Object->>java.util.AbstractCollection:extends
java.util.AbstractCollection->>java.util.AbstractList:extends
java.util.AbstractList->>java.util.List:implements
```
```
public abstract class AbstractList
extends AbstractCollection
implements List
public abstract class AbstractCollection
extends Object
implements Collection
```
The AbstractList Class is an Abstract Class extends another Abstract Class AbstractCollection and implements List interface .Note AbstractCollection , the abstract class which implements Collection interface and extends the Object class , the parent class of all the classes. The AbstractList is the foundation of other classes such as ArrayList, which supports dynamic arrays.
Division of AbstractList
```mermaid
graph TD;
Object-->|extends| AbstractCollection;
Object-->|extends|CopyOnWriteArrayList;
AbstractCollection-->|implements| Collection;
AbstractList-->|extends|AbstractCollection;
List-->|implements|AbstractList;
List-->|implements|CopyOnWriteArrayList;
AbstractList-->|extends|ArrayList;
AbstractList-->|extends|AbstractSequentialList;
AbstractList-->|extends|Vector;
AbstractSequentialList-->|extends|LinkedList;
```
Note: The Vector class is deprecated since Java 5. Deprecated means it is supported but less in use or not recommended. Where as, ArrayList and LinkedList are widely used in Java programming.
Array List
- 1. Java ArrayList class can contain duplicate elements.
- 2. Java ArrayList class maintains insertion order.
- 3.Java ArrayList class is non synchronized. Note: Vector class of Java is synchronized .
- 4.Java ArrayList allows random access because the array works on an index basis.
- 5.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.
- 6.ArrayList in Java can be seen as a VECTOR in C++ STL library.
- 7.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.That is it follows : Generic characteristics.
- 1. ArrayList().
- 2. ArrayList( Collection < ? extends E > c ) .
- 3. ArrayList( int capacity ) .
- 1. add( int index, Object element ) .
- 2. add(Object o) .
- 3. addAll ( Collection C ) .
- 4. addAll ( int index , Collection C ) .
- 5. clear() .
- 6. clone() .
- 7. contains ( Object o ) .
- 8. ensureCapacity ( int minCapacity ) .
- 9. forEach?(Consumer < ? super E > action) .
- 10. get ( int index ) .
- 11.indexOf ( Object O) .
- 12. isEmpty ( ) .
- 13. lastIndexOf ( Object O ) .
- 14. Iterator ( ) .
- 15. listIterator ( ) .
- 16. listIterator( int index) .
- 17. remove ( Object o ) .
- 18. remove ( int index ) .
- 19. removeAll ( Collection c ) .
- 20. removeIf ( Predicate filter ) .
- 21. removeRange ( int fromIndex, int toIndex ) .
- 22. retainAll ( Collection c ) .
- 23. set (int index, E element) .
- 24. size() .
- 25. spliterator() .
- 26. subList(int fromIndex, int toIndex) .
- 27. Object[] toArray() .
- 28. toArray( Object[] O) .
- 29. sort( Comparator < ? super E > c ) .
- 30. trimToSize() .
- Synchronization of Array List-Example
The ArrayList class is an array class that can grow or shrink at runtime . Note that arrays of this class must hold objects, not just simple data types.The ArrayList class extends AbstractList and implements the List interface.ArrayList is a generic class that has this declaration:
```mermaid
sequenceDiagram
java.util.Collection->>java.util.AbstractCollection:implements
java.lang.Object->>java.util.AbstractCollection:extends
java.util.AbstractCollection->>java.util.AbstractList:extends
java.util.AbstractList->>java.util.List:implements
java.util.ArrayList->>java.util.AbstractList:extends
java.util.ArrayList->>java.util.List:implements
java.util.ArrayList->>java.lang.Cloneable:implements
java.util.ArrayList->>java.io.Serializable:implements
java.util.ArrayList->>java.util.RandomAccess:implements
```
```
public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
//Others
---------------------------------------
public abstract class AbstractList
extends AbstractCollection
implements List
public abstract class AbstractCollection
extends Object
implements Collection
--------------------------------
Class/Interface Package
-------------- ----------
ArrayList java.util
AbstractList java.util
List java.util
RandomAccess java.util
Cloneable java.lang
Serializable java.io
AbstractCollection java.util
Object java.lang
Collection java.util
```
Characteristic of ArrayList are:

Constructors Of ArrayList
```Syntax
Definition: The above constructor builds an empty array list.
```
```Syntax
Definition: This constructor builds an array list,
that is initialized with the elements of the collection c.
```
```Syntax
Definition: This constructor builds an array list that has the initial capacity.
Capacity: The capacity is the size of the underlying array that is used to store the elements .
The capacity grows automatically as elements are added to an array list.
```
Methods of ArrayList
```Syntax
Definition: This method is used to insert a specific element,
at a specific position index in a list.
Note:
In the above example :
for (int i = 0; i < arrayList.size(); i++) {
if(i==1){
arrayList.add(i,"world");
}
}
When we get the index = 1 , and it will add
world at index : 1 .
And it will add the element and size of the ArrayList will get,
increased. And the previous element existed at index 1 will become 2.
```
```Syntax
Definition: It is used to append the specified element at the end of a list.
Like:
arrayList.add(1);
[1]
Then if we add:
arrayList.add(2);
It will be:
[1,2]
i.e. It will add element from end.
```
```Syntax
Definition: This method is used to append all the elements ,
from a specific collection to the end of the mentioned list,
in such an order that the values are returned by the specified,
collection’s iterator.
:If the ArrayList is Raw Type:
--------------------------------
List add any type of element dynamically,
Without type checking.
:If the ArrayList is Generic Type:
--------------------------------
List add that specific type of element dynamically,
With type checking.
```
```Syntax
Definition: Used to insert all of the elements ,
starting at the specified position from a ,
specific collection into the mentioned list.
:If the ArrayList is Raw Type:
--------------------------------
List add any type of element dynamically,
Without type checking.
:If the ArrayList is Generic Type:
--------------------------------
List add that specific type of element dynamically,
With type checking.
```
```Syntax
Definition: This method is used to remove all the elements from any list.
```
```Syntax
Definition: This method is used to return a shallow copy of an ArrayList.
```
```Syntax
Definition: Returns (Boolean) true if this list contains the specified element.
```
```Syntax
Definition: Increases the capacity of this ArrayList instance, if necessary,
to ensure that it can hold at least the number of elements specified by the
minimum capacity argument.
```
```Syntax
Definition: Performs the given action for each element of the Iterable,
until all elements have been processed or the action throws an exception.
```
```Syntax
Definition: Returns the element at the specified position in this list.
```
```Syntax
Definition: The index the first occurrence of a specific element is either returned,
or -1 in case the element is not in the list. That is it returns Integer which is
an index .
```
```Syntax
Definition: Returns true if this list contains no elements.
```
```Syntax
Definition: The index of the last occurrence of a specific element ,
is either returned or -1 in case the element is not in the list.
: i.e. :
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("!");
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("!");
arrayList.lastIndexOf("Hello") = 3
```
```Syntax
Definition: Returns an iterator over the elements in this list ,
in proper sequence.
```
```Syntax
Definition: Returns a list iterator over the elements in this list
(in proper sequence).
```
```Syntax
Definition: Returns a list iterator over the elements in this list (in proper sequence),
starting at the specified position in the list.
```
```Syntax
Definition:
Removes the first occurrence of the specified element from this list,
if it is present. If the list does not contain the element, it is unchanged.
More formally, removes the element with the lowest index i
such that Objects.equals(o, get(i)) (if such an element exists).
Returns true if this list contained the specified element (or equivalently,
if this list changed as a result of the call).
```
```Syntax
Definition: Removes the element at the specified position in this list.
```
```Syntax
Definition: Removes from this list all of its elements ,
that are contained in the specified collection.
```
```Syntax
Definition: Removes all of the elements of this collection that satisfy the given predicate.
```
```Syntax
Definition: Removes from this list all of the elements whose index is between
fromIndex, inclusive, and toIndex, exclusive.
Note: To implement the above function we have to make the class a sub class of
ArrayList class , and then implement, otherwise not visible as it is
a function having modifier protected, which let users not to use it directly.
Eg:
class ArrayList22 extends ArrayList{
public static void main(String[] args) {
ArrayList22 arrayList = new ArrayList22();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(4);
arrayList.add(5);
System.out.println(arrayList);
arrayList.removeRange(1, 3);
}
}
```
```Syntax
Definition: Retains only the elements in this list that are contained in the
specified collection. One can tell it gives the intersection part.
```
```Syntax
Definition: Sets or Replaces the element at the specified position ,
in this list with the specified element or at a given index.
```
```Syntax
Definition: Returns the number of elements in this list.
```
```Syntax
Definition: Creates a late-binding and fail-fast ,
Spliterator over the elements in this list.
```
```Syntax
Definition: Returns a view of the portion of this list,
between the specified fromIndex, inclusive, and toIndex, exclusive.
(If fromIndex and toIndex are equal, the returned list is empty.)
For Generic Types:
ArrayList arrayList = new ArrayList<>();
List arr = arrayList.subList(fromIndex,toIndex);
AbstractList arr1 = (AbstractList) arrayList.subList(fromIndex, toIndex);
//A cast for AbstractList
For Raw Types:
ArrayList arrayList1 = new ArrayList();
List arr2 = arrayList1.subList(0, 1);
AbstractList arr3 = (AbstractList) arrayList1.subList(0, 1);
//A cast for AbstractList
```
```Syntax
Definition: Returns an array containing all of the elements,
in this list in proper sequence (from first to last element).
```
```Syntax
Definition: It is also used to return an array containing all of the elements,
in this list in the correct order.
```
```Syntax
Definition: Sorts this list according to the order ,
induced by the specified Comparator.
```
```Syntax
Definition: Trims the capacity of this ArrayList instance,
to be the list's current size. An application can use this,
operation to minimize the storage of an ArrayList instance.
```
Methods
Definition
1.add( int index, Object element )
Definition: This method is used to insert a specific element,
at a specific position index in a list.
2. add(Object o)
Definition: It is used to append the specified element at the end of a list.
3.addAll ( Collection C )
Definition: This method is used to append all the elements ,
from a specific collection to the end of the mentioned list,
in such an order that the values are returned by the specified,
collection’s iterator.
4.addAll ( int index , Collection C )
Definition: Used to insert all of the elements ,
starting at the specified position from a ,
specific collection into the mentioned list.
5.clear()
Definition: This method is used to remove all the elements from any list.
6. clone()
Definition: This method is used to return a shallow copy of an ArrayList.
7. contains ( Object o )
Definition: Returns (Boolean) true if this list contains the specified element.
8. ensureCapacity ( int minCapacity )
Definition: Increases the capacity of this ArrayList instance, if necessary,
to ensure that it can hold at least the number of elements specified by the
minimum capacity argument.
9. forEach(Consumer < ? super E > action)
Definition: Performs the given action for each element of the Iterable,
until all elements have been processed or the action throws an exception.
10. get ( int index )
Definition: Returns the element at the specified position in this list.
11. indexOf ( Object O)
Definition: The index the first occurrence of a specific element is either returned,
or -1 in case the element is not in the list. That is it returns Integer which is
an index .
12. isEmpty ( )
Definition: Returns true if this list contains no elements.
13. lastIndexOf ( Object O )
Definition: The index of the last occurrence of a specific element ,
is either returned or -1 in case the element is not in the list.
14. Iterator ( )
Definition: Returns an iterator over the elements in this list ,
in proper sequence.
15. listIterator ( )
Definition: Returns a list iterator over the elements in this list
(in proper sequence).
16. listIterator( int index)
Definition: Returns a list iterator over the elements in this list (in proper sequence),
starting at the specified position in the list.
17. remove ( Object o )
Definition: Removes the first occurrence of the specified element from this list,
if it is present. If the list does not contain the element, it is unchanged.
More formally, removes the element with the lowest index i
such that Objects.equals(o, get(i)) (if such an element exists).
Returns true if this list contained the specified element (or equivalently,
if this list changed as a result of the call).
18. remove ( int index )
Definition: Removes the element at the specified position in this list.
19. removeAll ( Collection c )
Definition: Removes from this list all of its elements ,
that are contained in the specified collection.
20. removeIf ( Predicate filter )
Definition: Removes all of the elements of this collection that satisfy the given predicate.
21. removeRange ( int fromIndex, int toIndex )
Definition: Removes from this list all of the elements whose index is between
fromIndex, inclusive, and toIndex, exclusive.
22. retainAll ( Collection c )
Definition: Retains only the elements in this list that are contained in the
specified collection. One can tell it gives the intersection part.
23. set (int index, E element)
Definition: Sets or Replaces the element at the specified position ,
in this list with the specified element or at a given index.
24. size()
Definition: Returns the number of elements in this list.
25. spliterator()
Definition:Creates a late-binding and fail-fast ,
Spliterator over the elements in this list.
26. subList(int fromIndex, int toIndex)
Definition:Returns a view of the portion of this list,
between the specified fromIndex, inclusive, and toIndex, exclusive.
(If fromIndex and toIndex are equal, the returned list is empty.).
27. Object[] toArray()
Definition: Returns an array containing all of the elements,
in this list in proper sequence (from first to last element).
28. toArray( Object[] O)
Definition: It is also used to return an array containing all of the elements,
in this list in the correct order.
29. sort( Comparator < ? super E > c )
Definition: Sorts this list according to the order ,
induced by the specified Comparator.
30. trimToSize()
Definition: Trims the capacity of this ArrayList instance,
to be the list's current size. An application can use this,
operation to minimize the storage of an ArrayList instance.
Synchronization of Array List
ArrayList is not synchronized by default.If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. We can achieve synchronizing Array List by using Collections.synchronizedList() method. The method returns a Synchronized(thread-safe) list backed by the specified list.
Example Of Synchronization of Array List
```Syntax
Representation:
Collections.synchronizedList() can be represented as,
java.util.Collections.synchronizedList(List list)
Also inside Collection interface it is defined as:
public static List synchronizedList(List list) .
Here T represents generic.
Example:
List list = Collections.synchronizedList(new ArrayList<>());
List list1 = Collections.synchronizedList(new ArrayList<>());
: And :
synchronized (list) {...}
Here synchronized is a keyword of Java.
And synchronized can be used as return type of a method.
When it becomes return type of a method , it returns a
thread-safe and synchronized keyword helps in
multi-threaded synchronization activity.
```
Representation of List as Multi Dimensional Array
We know that arr[ ] [ ] => 1st [ ] indicates rows and 2nd [ ] indicates columns .As it increases on rows and creates 2D i.e. Two dimensional whicb means it will have length ( height) and breadth ( width ). Single row means 1D i.e. one dimensional having length only. Where as in 3D - Three Dimensional Array we have row , columns and no . of blocks that contains columns and rows. We can create similar MultiDimensional Array in List through a technique called : Nesting List . Which we can also call as Multidimensional Collections or Nested Collections .
2 - Dimensional
Consider an example :
Creating 2 DImensional List - Eg
```Syntax
List> list1 = new ArrayList<>();
Which means no. of lists can be nested into a single list.
Say,
List list2 = new ArrayList<>();
list2.add(1);
list2.add(2);
list2.add(3);
And,
list1.add(list2);
The ouput we will get is :
[[1,2,3]]
It can be in terms of rows and columns:
rows = 0 , and number of columns = 3
Which can be accessed by:
list1.get(0).get(0)
list1.get(0).get(1)
list1.get(0).get(2)
Again:
List list3 = new ArrayList<>();
list3.add(4);
list3.add(5);
list3.add(6);
list1.add(list2);
The ouput we will get is :
[[1,2,3],[4,5,6]]
It can be in terms of rows and columns:
rows = 0 , and number of columns = 3
rows = 1 , and number of columns = 3
And row1 can be accessed by:
list1.get(1).get(0)
list1.get(1).get(1)
list1.get(1).get(2)
Now to iterate over each index :
Either our approach will be for each loop:
for (List list : list1) {
for (Integer integer : list) {
System.out.println(integer);
}
}
:Or by simple for loop:
for(int i = 0; i < list1.size(); i++){
for(int j = 0; j < list1.get(i).size(); j++){
System.out.println(list1.get(i).get(j));
}
}
```
3 - Dimensional
Consider an example :
Creating 3 DImensional List - Eg
```Syntax
Like Above:
List>> list1 = new ArrayList<>();
List> list2 = new ArrayList<>();
List list3 = new ArrayList<>();
list3.add(1);
list3.add(2);
list3.add(3);
list2.add(list3);
List list4 = new ArrayList<>();
list4.add(4);
list4.add(5);
list4.add(6);
list2.add(list4);
list1.add(list2);
System.out.println(list1);
[[[1, 2, 3], [4, 5, 6]]]
Hence :
list1.get(0).get(0).get(0) = 1
list1.get(0).get(0).get(1) = 2
list1.get(0).get(0).get(2) = 3
....etc.
Just Like :
arr[0][0][0] =1
arr[0][0][1] =2
arr[0][0][2] =3
...etc.
i.e.
0th Block , row=0,column =0 => 1
0th Block , row=0,column =1 => 2
0th Block , row=0,column =2 => 3
...etc.
Hence Nested Lists can create ,
Multi-Dimensional like arrays .
```
Optimizing the Nested Lists
Making numerous Lists again and again like above examples makes code bigger and with huge line of codes. To make it small we can:
1) Apply Anonymous Nested Inner Class.
1.a) Applying Anonymous Nested Inner Class to add element in a 2 Dimensional Structure
```Syntax
Example:
List> list1 = new ArrayList<>();
list1.add(new ArrayList<>() {
{
add(1);
add(2);
add(3);
}
});
list1.add(new ArrayList<>() {
{
add(4);
add(5);
add(6);
}
});
```
1.b) Applying Anonymous Nested Inner Class to add element in a 3 Dimensional Structure
```Syntax
Example:
List>> list1 = new ArrayList<>();
list1.add(new ArrayList<>() {
{
add(new ArrayList<>() {
{
add(1);
add(2);
add(3);
}
});
add(new ArrayList<>() {
{
add(4);
add(5);
add(6);
}
});
}
});
list1.add(new ArrayList<>() {
{
add(new ArrayList<>() {
{
add(7);
add(8);
add(9);
}
});
add(new ArrayList<>() {
{
add(10);
add(11);
add(12);
}
});
}
});
```
2) Apply Arrays.asList(varargs) .
2.a) Applying Arrays.asList(varargs) to add element in a 2 Dimensional Structure
```Syntax
Example:
List> list = new ArrayList<>();
list.add(new ArrayList<>(Arrays.asList(1,2,3)) );
list.add(new ArrayList<>(Arrays.asList(4,5,6)) );
```
2.b) Applying Arrays.asList(varargs) to add element in a 3 Dimensional Structure
```Syntax
Example:
List>> list = new ArrayList<>();
list.add(new ArrayList<>(Arrays.asList(
new ArrayList<>(Arrays.asList(1,2,3)),
new ArrayList<>(Arrays.asList(4,5,6))
)));
list.add(new ArrayList<>(Arrays.asList(
new ArrayList<>(Arrays.asList(7,8,9)),
new ArrayList<>(Arrays.asList(10,11,12))
)));
```
Note: Arrays is a Class of java's util package and asList() is a function which takes an array of element and convert them to list structure. This have less line of code and is the most optimised way to use from all of the above examples.
Abstract Sequential List
```mermaid
sequenceDiagram
java.util.Collection->>java.util.AbstractCollection:implements
java.lang.Object->>java.util.AbstractCollection:extends
java.util.AbstractCollection->>java.util.AbstractList:extends
java.util.AbstractList->>java.util.List:implements
java.util.AbstractSequentialList->>java.util.AbstractList:extends
java.util.LinkedList->>java.util.AbstractSequentialList:extends
```
```
public abstract class AbstractSequentialList
extends AbstractList
public class LinkedList
extends AbstractSequentialList
//Others
--------------------------------------------
public abstract class AbstractList
extends AbstractCollection
implements List
public abstract class AbstractCollection
extends Object
implements Collection
------------------------------
```
- 1. Abstract SequentialList is an abstract class in Java Collection .
- 2. It is a part of the Java Collection Framework .
- 3. It extends Abstract List class .
- 4. Now as Abstract List extends Abstract Collection and implements List, Abstract SequentialList inherits Abstract Collection class and List interface .
- 5.Also as Abstract Collection extends Object class and implements Collection interface , hence Abstract List class inherits them too.
- 6.This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list).
- 7.As Abstract List is an abstract class , it must be implemented by Linked List class which implements it.
Example of Abstract Sequential List
Linked List
```mermaid
sequenceDiagram
java.util.Collection->>java.util.AbstractCollection:implements
java.lang.Object->>java.util.AbstractCollection:extends
java.util.AbstractCollection->>java.util.AbstractList:extends
java.util.AbstractList->>java.util.List:implements
java.util.AbstractSequentialList->>java.util.AbstractList:extends
java.util.LinkedList->>java.util.AbstractSequentialList:extends
java.util.LinkedList->>java.util.Deque:implements
java.util.LinkedList->>java.lang.Cloneable:implements
java.util.LinkedList->>java.io.Serializable:implements
java.util.LinkedList->>java.util.List:implements
```
```
public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, Serializable
//Others
------------------------------------------------
public abstract class AbstractSequentialList
extends AbstractList
public class LinkedList
extends AbstractSequentialList
public abstract class AbstractList
extends AbstractCollection
implements List
public abstract class AbstractCollection
extends Object
implements Collection
-------------------------------------------------
```
- 1. Linked List class is a part of the Collection framework present in java.util package. .
- 2. LinkedList class extends AbstractSequentialList , an abstract class which provide skeletal framework of LinkedList class.
- 3. LinkedList class implements List interface , Deque interface, Cloneable interface and Serializable interface.
- 4. Linked List class is an implementation of the LinkedList data structure.
- 5. LinkedList data structure is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements that are added in a LinkedList data structure, are linked using pointers and addresses. Each element is known as a node.
- 6. As elements are added dynamically by LinkedList class, size also increases accordingly. And there is no need for extra functionality to increase the size of Linked List.
- 7. Internally, the LinkedList is implemented using the doubly Linked List Data Structure. A doubly linked list contains an extra pointer, typically called the previous pointer, together with the next pointer and data .
- 8.LinkedList is not synchronized .
- 1. Methods in Linked List and Array List
- 1. addFirst(E e)
- 2. addLast(E e)
- 3. descendingIterator()
- 4. element()
- 5. getFirst()
- 6. getLast()
- 7. offer(E e)
- 8.offerFirst(E e)
- 9.offerLast(E e)
- 10.peek()
- 11.peekFirst()
- 12.peekLast()
- 13.poll()
- 14.pollFirst()
- 15.pollLast()
- 16.push()
- 17.pop()
- 18.remove()
- 19.removeFirst()
- 20.removeLast()
- 21.removeFirstOccurrence(Object o)
- 22.removeLastOccurrence(Object o)
- 23.toString()
- Synchronization of Linked List-Example

Constructors of Linked List Class
1. LinkedList()
```Syntax
Generic Type:
LinkedList list = new LinkedList<>();
Raw Type:
LinkedList list = new LinkedList();
Def: This constructor is used to create an empty linked list.
```
2. LinkedList(Collection C)
```Syntax
Generic Type:
Collection collection = new ArrayList();
LinkedList list = new LinkedList(collection);
Raw Type:
Collection collection1 = new ArrayList();
LinkedList list1 = new LinkedList();
Def: Constructs a list containing the elements,
of the specified collection,
in the order they are returned,
by the collection's iterator.
```
Methods of Linked List Class
1. The Methods that go with Linked List and Array List.
Note: ensureCapacity ( int minCapacity ) , removeRange ( int fromIndex, int toIndex ), sort( Comparator < ? super E > c ), trimToSize ( ) , available to ArrayList Class but not available to LinkedList class due to the characteristics : 1) Size adjusted dynamically and 2) Addition of elements based on Doubly Linked List Data Structure.
2. New Methods of Linked List Class.
```Syntax
Def : It is used to insert the given element at the beginning of a list.
```
```Syntax
Def : It is used to append the given element to the end of a list.
```
```Syntax
Def : Returns an iterator over the elements in this deque,
in reverse sequential order.
The elements will be returned in order from last (tail) to first (head).
```
```Syntax
Def : Returns the first element/Retrieves the first element without,
removing it from the list.
```
```Syntax
Def : Returns the first element in this list.
```
```Syntax
Def : Returns the last element in this list.
```
```Syntax
Def: Adds the specified element as the tail
(last element) of this list.
```
```Syntax
Def: Inserts the specified element at the front of this list.
```
```Syntax
Def: Inserts the specified element at the end of this list.
```
```Syntax
Def: Retrieves, the head (first element) of this list,but does not remove it.
```
```Syntax
Def: Retrieves, the first element of this list,
or returns null if this list is empty, but does not remove it.
```
```Syntax
Def: Retrieves, the last element of this list,
or returns null if this list is empty,but does not remove it.
```
```Syntax
Def: Retrieves and removes the head (first element) of this list.
```
```Syntax
Def: Retrieves and removes the first element of this list,
or returns null if this list is empty.
```
```Syntax
Def: Retrieves and removes the last element of this list,
or returns null if this list is empty.
```
```Syntax
Def: Pushes an element onto the stack represented by this list.
In other words, inserts the element at the front of this list.
```
```Syntax
Def: Pops an element from the stack represented by this list.
In other words, removes and returns the first element of this list.
```
```Syntax
Def: Retrieves and removes the head (first element) of this list.
```
```Syntax
Def: Removes and returns the first element from this list.
```
```Syntax
Def: Removes and returns the last element from this list.
```
```Syntax
Def: Removes the first occurrence of the specified element in this list
(when traversing the list from head to tail).
If the list does not contain the element, it is unchanged.
```
```Syntax
Def: Removes the last occurrence of the specified element in this list
(when traversing the list from head to tail).
If the list does not contain the element, it is unchanged.
```
And From AbstractCollection
```Syntax
Def: Returns a string representation of this collection.
The string representation consists of a list of the collection's elements,
in the order they are returned by its iterator, enclosed in square brackets ("[]").
Adjacent elements are separated by the characters ", " (comma and space).
```
New Methods in Linked List
Definition
1. addFirst(E e)
Definition: It is used to insert the given element at the beginning of a list.
2. addLast(E e)
Definition: It is used to append the given element to the end of a list.
3. descendingIterator()
Definition: Returns an iterator over the elements in this deque,
in reverse sequential order. The elements will be returned in order from last (tail) to first (head).
4. element()
Definition: Returns the first element/Retrieves the first element without,
removing it from the list.
5. getFirst()
Definition: Returns the first element in this list.
6. getLast()
Definition: Returns the last element in this list.
7. offer(E e)
Definition: Adds the specified element as the tail
(last element) of this list.
8. offerFirst(E e)
Definition: Inserts the specified element at the front of this list.
9. offerLast(E e)
Definition: Inserts the specified element at the end of this list.
10. peek()
Definition: Retrieves, the head (first element) of this list,but does not remove it.
11. peekFirst()
Definition: Retrieves, the first element of this list,
or returns null if this list is empty, but does not remove it.
12. peekLast()
Definition: Retrieves, the last element of this list,
or returns null if this list is empty,but does not remove it.
13. poll()
Definition: Retrieves and removes the head (first element) of this list.
14. pollFirst()
Definition: Retrieves and removes the first element of this list,
or returns null if this list is empty.
15. pollLast()
Definition: Retrieves and removes the last element of this list,
or returns null if this list is empty.
16. push()
Definition: Pushes an element onto the stack represented by this list.
In other words, inserts the element at the front of this list.
17. pop()
Definition: Pops an element from the stack represented by this list.
In other words, removes and returns the first element of this list.
18. remove()
Definition: Retrieves and removes the head (first element) of this list.
19. removeFirst()
Definition: Removes and returns the first element from this list.
20. removeLast()
Definition: Removes and returns the last element from this list.
21. removeFirstOccurrence(Object o)
Definition: Removes the first occurrence of the specified element in this list
(when traversing the list from head to tail).
If the list does not contain the element, it is unchanged.
22. removeLastOccurrence(Object o)
Definition: Removes the last occurrence of the specified element in this list
(when traversing the list from head to tail).
If the list does not contain the element, it is unchanged.
Inherit from Class/Interface
Method/s
Definition
AbstractCollection
23. toString()
Definition: Returns a string representation of this collection.
The string representation consists of a list of the collection's elements,
in the order they are returned by its iterator, enclosed in square brackets ("[]").
Adjacent elements are separated by the characters ", " (comma and space).
Synchronization of Linked List
LinkedList is not synchronized by default.If multiple threads access an LinkedList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. We can achieve synchronizing Linked List by using Collections.synchronizedList() method. The method returns a Synchronized(thread-safe) list backed by the specified list.
Example Of Synchronization of Linked List
```Syntax
Representation:
Collections.synchronizedList() can be represented as,
java.util.Collections.synchronizedList(List list)
Also inside Collection interface it is defined as:
public static List synchronizedList(List list) .
Here T represents generic.
Example:
List list = Collections.synchronizedList(new LinkedList<>());
List list1 = Collections.synchronizedList(new LinkedList<>());
: And :
synchronized (list) {...}
Here synchronized is a keyword of Java.
And synchronized can be used as return type of a method.
When it becomes return type of a method , it returns a
thread-safe and synchronized keyword helps in
multi-threaded synchronization activity.
```
Vectors
```mermaid
sequenceDiagram
java.util.Vector->>java.util.AbstractList:extends
java.util.Vector->>java.util.List:implements
java.util.Vector->>java.util.RandomAccess:implements
java.util.Vector->>java.lang.Cloneable:implements
java.util.Vector->>java.io.Serializable:implements
java.util.AbstractCollection->>java.util.Collection:implements
java.util.AbstractCollection->>java.lang.Object:extends
java.util.AbstractList->>java.util.AbstractCollection:extends
java.util.AbstractList->>java.util.List:implements
```
- 1. Vector is like the dynamic array which can grow or shrink its size.
- 2. Vector contains element can be accessed by its index just like an array.
- 3. Vector is just similar to Array List class can insert element, updated or removed .
- 4. Unlike ArrayList , Vector is synchronized.
- 5. Like ArrayList class , Vector Class allows random access.
- 6. Like ArrayList class , Vector Class maintains insertion order.
- 7. Like ArrayList class , Vector Class can contain duplicate elements.
- 8. As ArrayList is not synchronised and Vector Class is synchronized , ArrayList is faster than Vector Class i.e. Vector Class is slower than ArrayList.
- 9. The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the ConcurrentModificationException.
- 10. We cannot create a Vector of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class.That is it follows : Generic characteristics.
- 11. if we open Vector class , we will able to see that:
- int capacityIncreament: Contains the increment value.
- int elementCount: Number of elements currently in vector stored in it.
- Object elementData[]: Array that holds the vector is stored in it.
```
public class Vector
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
//Others
---------------------------------------
public abstract class AbstractList
extends AbstractCollection
implements List
public abstract class AbstractCollection
extends Object
implements Collection
--------------------------------
```
```Syntax
public class Vector
extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable
{
protected Object[] elementData;
protected int elementCount;
protected int capacityIncrement;
}
```
Vector defines three protected data members:
Constructors of Vector Class
1. vector()
```Syntax
Def: It constructs an empty vector with the default size as 10.
Default Size of Vector: 10
Default Initial Capacity Increment: 0
As we can see in Vector Class constructor:
public class Vector
extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable
{
....
public Vector(int initialCapacity) {
this(initialCapacity, capacityIncrement: 0);
}
public Vector() {
this(initialCapacity: 10);
}
....
}
By default, the vector increases its capacity by double.
```
2. vector(int initialCapacity)
```Syntax
Def: It constructs an empty vector with the specified initial capacity
and with its capacity increment equal to zero.
```
3. vector(int initialCapacity,int capacityIncrement)
```Syntax
Def: It constructs an empty vector with the specified initial capacity
and capacity increment.
Note: If an increment is specified in its constructor,
Vector will grow in accordance with it in each allocation cycle.
```
4. Vector( Collection extends E> c)
```Syntax
Def: It constructs a vector that contains the elements of a collection c.
```
Methods of Vector Class
-
1)Performance: Due to synchronization in Vector can lead to slower performance that other efficient classes used in Collection framework of Java such as "ArrayList" . -
2) Legacy Codes: Due to the legacy methods exists and the codes are written with those methods(Legacy codes ) so it get harder to find support for those codes as compared to other newer classes of Collection framework . -
3) Unnecessary Overhead: If we don’t need the synchronization features of Vector, but if we are using the class , then it will cause unnessary overhead.
1. Methods of Vector Class (That contains in Array List )
Note:All the methods that contains and discussed in Array List are also in Vector class given here.
Legacy Support of Vector Class: There are some methods that doesnot contain in ArrayList class but have in Vector class considered to be extras , and the methods that are in Linked List class are justified according to the data structure that it follows . These extra methods of Vector class are considered as "Legacy Methods" or old methods that are used in old times since it has been introduced in Java and carried forward . According to the history of Vector, it has been used as class template in STL Library of C++ around 1994 and it had been incorporated as a "Class" in "Java in JDK 1.0 since 1996, hence it falls under Legacy class or an old class and as of the Java 2 platform v1.2 i.e. around 1998, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Hence it has "Legacy Support" i.e. using "Legacy Methods" that are used earlier can be implemented in mordern times under compatibility support of "Collection framework".
Extra Methods of Vector Class.
1. addElement(E obj)
```Syntax
Def: Adds the specified component to the end of this vector,
increasing its size by one.
The capacity of this vector is increased ,
if its size becomes greater than its capacity.
```
2. capacity()
```Syntax
Def: Returns the current capacity of this vector.
The current capacity (the length of its internal data array,
kept in the field elementData of this vector)
```
3. copyInto(Object[] anArray)
```Syntax
Def: Copies the components of this vector into the specified array.
The item at index k in this vector is copied into component k of
an Array.
```
4. elementAt(int index)
```Syntax
Def: Returns the component at the specified index.
This method is identical in functionality to the get(int)
method (which is part of the List interface).
```
5. elements()
```Syntax
Def: Returns an enumeration of the components of this vector.
The returned Enumeration object will generate all items in this vector.
The first item generated is the item at index 0,
then the item at index 1, and so on. If the vector is ,
structurally modified while enumerating over the elements ,
then the results of enumerating are undefined.
```
6. firstElement()
```Syntax
Def: Returns the first component (the item at index 0) of this vector.
```
7. indexOf(Object o, int index)
```Syntax
Def: Returns the index of the first occurrence of the specified element,
in this vector, searching forwards from index,
or returns -1 if the element is not found.
Eg:
Vector vector = new Vector<>();
vector.addElement(4);
int j = vector.indexOf(5, 0);
Returns: -1
(Element 5 is not found at
index 0)
Again:
int j = vector.indexOf(4, 1);
Returns: -1
(Element 4 is not found at
index 1)
Now:
Vector vector = new Vector<>();
vector.addElement(1);
vector.addElement(2);
vector.addElement(3);
vector.addElement(4);
Integer i = vector.indexOf(3, 0);
System.out.println(i);
It will start searching element 3 from
index 0 and it will return 2 (index no)
where the element 3 exists.
```
8. insertElementAt(E obj, int index)
```Syntax
Def: Inserts the specified object as a component in this vector,
at the specified index.
Each component in this vector with an index,
greater or equal to the specified index is shifted upward,
to have an index one greater than the value it had previously.
```
9. lastElement()
```Syntax
Def: Returns the last component of the vector.
```
10. removeAllElements()
```Syntax
Def: Removes all components from this vector and sets its size to zero.
```
11. removeElement(Object obj)
```Syntax
Def: Removes the first (lowest-indexed) occurrence of the argument,
from this vector.
If the object is found in this vector,
each component in the vector with an index greater or equal
to the object's index is shifted downward to have an index
one smaller than the value it had previously.
Eg:
Vector vector = new Vector<>();
vector.addElement(3);
vector.addElement(3);
vector.removeElement(3);
Hence it will remove the first occurence
of the object 3.
System.out.println(vector); will return
[3] which is at index 1 previously ,
shifted to index 0 now.(downward )
```
12. removeElementAt(int index)
```Syntax
Def: Deletes the component at the specified index.
Each component in this vector with an index greater or
equal to the specified index is shifted downward ,
to have an index one smaller than the value that
it had previously. The size of this vector is decreased by 1.
```
13.replaceAll(UnaryOperator operator)
```Syntax
Def: Replaces each element of this list with the result
of applying the operator to that element.
Errors or runtime exceptions thrown by the operator
are relayed to the caller.
Note: It throws Null Pointer Exception ,
if the added element is null,
Eg:
Vector vector = new Vector<>();
vector.addElement(null);
vector.replaceAll(i -> i * 2);
System.out.println(vector);
Throws: NullPointerException
```
14.setElementAt(E obj, int index)
```Syntax
Def: Sets the component at the specified index of this vector,
to be the specified object.
The previous component at that position is discarded.
```
15.setSize(int newSize)
```Syntax
Def: Sets the size of this vector.
Note: If the new size is greater than the current size,
new null items are added to the end of the vector.
Eg:
Vector vector = new Vector<>();
vector.addElement(1);
System.out.println(vector);
vector.setSize(2);//greater than the previous
System.out.println(vector);
Output: [1,null]
Note: If the new size is less than the current size,
all components at index newSize and greater are discarded.
Eg:
Vector vector = new Vector<>();
vector.addElement(1);
vector.addElement(2);
vector.addElement(3);
vector.addElement(4);
System.out.println(vector);
vector.setSize(2);//Less than the previous
System.out.println(vector);
Output: [1,2]
Note:
if the new size is negative, then it throws
ArrayIndexOutOfBoundsException .
Eg:
Vector vector = new Vector<>();
vector.addElement(1);
System.out.println(vector);
vector.setSize(-1);//Negative Size
System.out.println(vector);
Output: ArrayIndexOutOfBoundsException
```
Extra Methods
Description
1. addElement(E obj)
Def: Adds the specified component to the end of this vector,
increasing its size by one.
The capacity of this vector is increased ,
if its size becomes greater than its capacity.
2. capacity()
Def: Returns the current capacity of this vector.
The current capacity (the length of its internal data array,
kept in the field elementData of this vector).
3. copyInto(Object[] anArray)
Def: Returns the component at the specified index.
This method is identical in functionality to the get(int)
method (which is part of the List interface).
4. elementAt(int index))
Def: Copies the components of this vector into the specified array.
The item at index k in this vector is copied into component k of
an Array.
5. elements()
Def: Returns an enumeration of the components of this vector.
The returned Enumeration object will generate all items in this vector.
The first item generated is the item at index 0,
then the item at index 1, and so on. If the vector is ,
structurally modified while enumerating over the elements ,
then the results of enumerating are undefined.
6. firstElement()
Def: Returns the first component (the item at index 0) of this vector.
7. indexOf(Object o, int index)
Def: Returns the index of the first occurrence of the specified element,
in this vector, searching forwards from index,
or returns -1 if the element is not found.
8. insertElementAt(E obj, int index)
Def: Inserts the specified object as a component in this vector,
at the specified index.
Each component in this vector with an index,
greater or equal to the specified index is shifted upward,
to have an index one greater than the value it had previously.
9. lastElement()
Def: Returns the last component of the vector.
10. removeAllElements()
Def: Removes all components from this vector and sets its size to zero.
11. removeElement(Object obj)
Def: Removes the first (lowest-indexed) occurrence of the argument,
from this vector.
If the object is found in this vector,
each component in the vector with an index greater or equal
to the object's index is shifted downward to have an index
one smaller than the value it had previously.
12. removeElementAt(int index)
Def: Deletes the component at the specified index.
Each component in this vector with an index greater or
equal to the specified index is shifted downward ,
to have an index one smaller than the value that
it had previously. The size of this vector is decreased by 1.
13. replaceAll(UnaryOperator operator)
Def: Replaces each element of this list with the result
of applying the operator to that element.
Errors or runtime exceptions thrown by the operator
are relayed to the caller.
Note: It throws Null Pointer Exception ,
if the added element is null.
14. setElementAt(E obj, int index)
Def: Sets the component at the specified index of this vector,
to be the specified object.
The previous component at that position is discarded.
15. setSize(int newSize)
Def: Sets the size of this vector.
If the new size is greater than the current size,
new null items are added to the end of the vector.
If the new size is less than the current size,
all components at index newSize and greater are discarded.if the new size is negative, then it throws
ArrayIndexOutOfBoundsException .