0% found this document useful (0 votes)
6 views29 pages

Java Collections Framework: A Comprehensive Guide

The document provides an overview of the Java Collection Framework, detailing its architecture, interfaces, and classes such as List, Set, and Queue. It explains the Collection and Iterator interfaces, their methods, and the implementation of classes like ArrayList, LinkedList, Vector, and Stack. Additionally, it includes examples of using these collections and their specific methods for manipulating data.

Uploaded by

piyush anand
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

Java Collections Framework: A Comprehensive Guide

The document provides an overview of the Java Collection Framework, detailing its architecture, interfaces, and classes such as List, Set, and Queue. It explains the Collection and Iterator interfaces, their methods, and the implementation of classes like ArrayList, LinkedList, Vector, and Stack. Additionally, it includes examples of using these collections and their specific methods for manipulating data.

Uploaded by

piyush anand
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Collections in Java

1. Java Collection Framework

2. Hierarchy of Collection Framework

3. Collection interface

4. Iterator interface

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList

, Vector, LinkedList

, PriorityQueue

, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The [Link] package
contains all the classes

and interfaces

for the Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as
follows:
No. Method Description

1 public boolean add(E e) It is used to insert an element in this


collection.

2 public boolean It is used to insert the specified collection


addAll(Collection<? elements in the invoking collection.
extends E> c)

3 public boolean It is used to delete an element from the


remove(Object element) collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> specified collection from the invoking
c) collection.

5 default boolean It is used to delete all the elements of the


removeIf(Predicate<? collection that satisfy the specified
super E> filter) predicate.

6 public boolean It is used to delete all the elements of


retainAll(Collection<?> c) invoking collection except the specified
collection.

7 public int size() It returns the total number of elements in


the collection.

8 public void clear() It removes the total number of elements


from the collection.

9 public boolean It is used to search an element.


contains(Object element)

10 public boolean It is used to search the specified collection


containsAll(Collection<?> in the collection.
c)

11 public Iterator iterator() It returns an iterator.


12 public Object[] toArray() It converts collection into array.

13 public <T> T[] It converts collection into array. Here, the


toArray(T[] a) runtime type of the returned array is that of
the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the


parallelStream() collection as its source.

16 default Stream<E> It returns a sequential Stream with the


stream() collection as its source.

17 default Spliterator<E> It generates a Spliterator over the specified


spliterator() elements in the collection.

18 public boolean It matches two collections.


equals(Object element)

19 public int hashCode() It returns the hash code number of the


collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if the iterator has more elements


hasNext() otherwise it returns false.

2 public Object It returns the element and moves the cursor pointer
next() to the next element.

3 public void It removes the last elements returned by the


remove() iterator. It is less used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all
the subclasses of Collection interface also implement the Iterable
interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

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.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.

The classes that implement the List interface are given below.

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.

import [Link].*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Output:

Ravi
Vijay
Ravi
Ajay

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list
internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.

import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:

Ravi
Vijay
Ravi
Ajay

Vector
Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods that
are not the part of Collection framework.

Consider the following example.

import [Link].*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Output:

Ayush
Amit
Ashish
Garima

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data
structure, i.e., Stack. The stack contains all of the methods of Vector class
and also provides its methods like boolean push(), boolean peek(),
boolean push(object o), which defines its properties.
Consider the following example.

import [Link].*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Output:

Ayush
Garvit
Amit
Ashish

Java 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 [Link] 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.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because the array works on an
index basis.
o 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.
o 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:
1. ArrayList<int> al = ArrayList<int>(); // does not work
2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

o 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.

Hierarchy of ArrayList class


As shown in the above diagram, the Java ArrayList class extends
AbstractList class which implements the List interface. The List interface
extends the Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration


Let's see the declaration for [Link] class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E


>, RandomAccess, Cloneable, Serializable

Constructors of ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection< It is used to build an array list that is initialized


? extends E> c) with the elements of the collection c.

ArrayList(int It is used to build an array list that has the


capacity) specified initial capacity.

Methods of ArrayList

Method Description

void add(int index, E It is used to insert the specified element


element) at the specified position in a list.
boolean add(E e) It is used to append the specified
element at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements


extends E> c) in the specified collection to the end of
this list, in the order that they are
returned by the specified collection's
iterator.

boolean addAll(int index, It is used to append all the elements in


Collection<? extends E> c) the specified collection, starting at the
specified position of the list.

void clear() It is used to remove all of the elements


from this list.

void ensureCapacity(int It is used to enhance the capacity of an


requiredCapacity) ArrayList instance.

E get(int index) It is used to fetch the element from the


particular position of the list.

boolean isEmpty() It returns true if the list is empty,


otherwise false.

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list


of the last occurrence of the specified
element, or -1 if the list does not contain
this element.

Object[] toArray() It is used to return an array containing


all of the elements in this list in the
correct order.

<T> T[] toArray(T[] a) It is used to return an array containing


all of the elements in this list in the
correct order.

Object clone() It is used to return a shallow copy of an


ArrayList.

boolean contains(Object o) It returns true if the list contains the


specified element.

int indexOf(Object o) It is used to return the index in this list


of the first occurrence of the specified
element, or -1 if the List does not
contain this element.

E remove(int index) It is used to remove the element present


at the specified position in the list.

boolean remove(Object o) It is used to remove the first occurrence


of the specified element.

boolean removeAll(Collection It is used to remove all the elements


<?> c) from the list.

boolean It is used to remove all the elements


removeIf(Predicate<? super from the list that satisfies the given
E> filter) predicate.

protected It is used to remove all the elements lies


void removeRange(int within the given range.
fromIndex, int toIndex)

void It is used to replace all the elements


replaceAll(UnaryOperator<E from the list with the specified element.
> operator)

void retainAll(Collection<?> It is used to retain all the elements in the


c) list that are present in the specified
collection.

E set(int index, E element) It is used to replace the specified


element in the list, present at the
specified position.

void sort(Comparator<? It is used to sort the elements of the list


super E> c) on the basis of the specified comparator.

Spliterator<E> spliterator() It is used to create a spliterator over the


elements in a list.

List<E> subList(int It is used to fetch all the elements that


fromIndex, int toIndex) lies within the given range.

int size() It is used to return the number of


elements present in the list.

void trimToSize() It is used to trim the capacity of this


ArrayList instance to be the list's current
size.
Java ArrayList Example
FileName: [Link]

import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}
Test it Now

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator


Let's see an example to traverse ArrayList elements using the Iterator
interface.

FileName: [Link]

import [Link].*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through Iterator
Iterator itr=[Link]();//getting the Iterator
while([Link]()){//check if iterator has the elements
[Link]([Link]());//printing the element and move to next
}
}
}
Test it Now

Output:

Mango
Apple
Banana
Grapes

Get and Set ArrayList


The get() method returns the element at the specified index, whereas
the set() method changes the element.

FileName: [Link]

1. import [Link].*;
2. public class ArrayListExample4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Mango");
6. [Link]("Apple");
7. [Link]("Banana");
8. [Link]("Grapes");
9. //accessing the element
10. [Link]("Returning element: "+[Link](1));//it will return t
he 2nd element, because index starts from 0
11. //changing the element
12. [Link](1,"Dates");
13. //Traversing list
14. for(String fruit:al)
15. [Link](fruit);
16.
17. }
18. }
Test it Now
Output:

Returning element: Apple


Mango
Dates
Banana
Grapes

How to Sort ArrayList


The [Link] package provides a utility class Collections, which has the
static method sort(). Using the [Link]() method, we can easily
sort the ArrayList.

FileName: [Link]

1. import [Link].*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. [Link]("Mango");
7. [Link]("Apple");
8. [Link]("Banana");
9. [Link]("Grapes");
10. //Sorting the list
11. [Link](list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. [Link](fruit);
15.
16. [Link]("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. [Link](21);
20. [Link](11);
21. [Link](51);
22. [Link](1);
23. //Sorting the list
24. [Link](list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. [Link](number);
28. }
29.
30. }

Output:

Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

Java 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.
The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting
needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class


As shown in the above diagram, Java LinkedList class extends
AbstractSequentialList class and implements List and Deque interfaces.

Doubly Linked List


In the case of a doubly linked list, we can add or remove elements from
both sides.

LinkedList class declaration


Let's see the declaration for [Link] class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implem


ents List<E>, Deque<E>, Cloneable, Serializabl

Java LinkedList Example

1. import [Link].*;
2. public class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Output: Ravi
Vijay
Ravi
Ajay

Java LinkedList example to add elements


Here, we see different ways to add elements.

1. import [Link].*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. [Link]("Initial list of elements: "+ll);
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ajay");
9. [Link]("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. [Link](1, "Gaurav");
12. [Link]("After invoking add(int index, E element)
method: "+ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. [Link]("Sonoo");
15. [Link]("Hanumat");
16. //Adding second list elements to the first list
17. [Link](ll2);
18. [Link]("After invoking addAll(Collection<? extend
s E> c) method: "+ll);
19. LinkedList<String> ll3=new LinkedList<String>();
20. [Link]("John");
21. [Link]("Rahul");
22. //Adding second list elements to the first list at specific positi
on
23. [Link](1, ll3);
24. [Link]("After invoking addAll(int index, Collection
<? extends E> c) method: "+ll);
25. //Adding an element at the first position
26. [Link]("Lokesh");
27. [Link]("After invoking addFirst(E e) method: "+ll)
;
28. //Adding an element at the last position
29. [Link]("Harsh");
30. [Link]("After invoking addLast(E e) method: "+ll)
;
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay,
Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Java LinkedList example to remove elements


Here, we see different ways to remove an element.

1. import [Link].*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. [Link]("Ravi");
8. [Link]("Vijay");
9. [Link]("Ajay");
10. [Link]("Anuj");
11. [Link]("Gaurav");
12. [Link]("Harsh");
13. [Link]("Virat");
14. [Link]("Gaurav");
15. [Link]("Harsh");
16. [Link]("Amit");
17. [Link]("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. [Link]("Vijay");
20. [Link]("After invoking remove(object) method:
"+ll);
21. //Removing element on the basis of specific position
22. [Link](0);
23. [Link]("After invoking remove(index) method: "
+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. [Link]("Ravi");
26. [Link]("Hanumat");
27. // Adding new elements to arraylist
28. [Link](ll2);
29. [Link]("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. [Link](ll2);
32. [Link]("After invoking removeAll() method: "+ll
);
33. //Removing first element from the list
34. [Link]();
35. [Link]("After invoking removeFirst() method: "
+ll);
36. //Removing first element from the list
37. [Link]();
38. [Link]("After invoking removeLast() method: "
+ll);
39. //Removing first occurrence of element from the list
40. [Link]("Gaurav");
41. [Link]("After invoking removeFirstOccurrence()
method: "+ll);
42. //Removing last occurrence of element from the list
43. [Link]("Harsh");
44. [Link]("After invoking removeLastOccurrence()
method: "+ll);
45.
46. //Removing all the elements available in the list
47. [Link]();
48. [Link]("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit,
Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav,
Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain
insertion order. Both are non-synchronized classes.

However, there are many differences between the ArrayList and


LinkedList classes that are given below.
ArrayList LinkedList

1) ArrayList internally uses LinkedList internally uses


a dynamic array to store the a doubly linked list to store
elements. the elements.

2) Manipulation with ArrayList Manipulation with LinkedList


is slow because it internally uses an is faster than ArrayList because
array. If any element is removed it uses a doubly linked list, so no
from the array, all the other bit shifting is required in
elements are shifted in memory. memory.

3) An ArrayList class can act as a LinkedList class can act as a


list only because it implements List list and queue both because it
only. implements List and Deque
interfaces.

4) ArrayList is better for storing LinkedList is better for


and accessing data. manipulating data.

5) The memory location for the The location for the elements of
elements of an ArrayList is a linked list is not contagious.
contiguous.

6) Generally, when an ArrayList is There is no case of default


initialized, a default capacity of 10 is capacity in a LinkedList. In
assigned to the ArrayList. LinkedList, an empty list is
created when a LinkedList is
initialized.

7) To be precise, an ArrayList is a LinkedList implements the


resizable array. doubly linked list of the list
interface.

Java Vector
Vector is like the dynamic array which can grow or shrink
its size. Unlike array, we can store n-number of elements in
it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in
the [Link] package and implements the List interface, so
we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-


safe implementation only. If you don't need to use the
thread-safe implementation, you should use the ArrayList,
the ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In


case of concurrent modification, it fails and throws the
ConcurrentModificationException.

It is similar to the ArrayList, but with two differences-

o Java Vector contains many legacy methods that are


not the part of a collections framework.
o Vector is synchronized.

Java Vector Methods


The following are the list of Vector class methods:

S Method Description
N

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection


Vector.

3) addElement() It is used to append the specified component to the end of this ve


the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.


6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specifi

9) copyInto() It is used to copy the components of the vector into the specified ar

10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use
ensures that the vector can hold at least the number of component
minimum capacity argument.

13) equals() It is used to compare the specified object with the vector for equalit

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the
elements have been processed or the action throws an exception.

16) get() It is used to get an element at the specified position in the vector.

17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specifie
vector. It returns -1 if the vector does not contain the element.

19) insertElementAt() It is used to insert the specified object as a component in the giv
specified index.

20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper se
22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the specifie
vector. It returns -1 if the vector does not contain the element.

24) listIterator() It is used to get a list iterator over the elements in the list in proper

25) remove() It is used to remove the specified element from the vector. If the
contain the element, it is unchanged.

26) removeAll() It is used to delete all the elements from the vector that are presen
collection.

27) removeAllElemen It is used to remove all elements from the vector and set the size
ts() zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the ar


vector.

29) removeElementAt It is used to delete the component at the specified index.


()

30) removeIf() It is used to remove all of the elements of the collection that
predicate.

31) removeRange() It is used to delete all of the elements from the vector whose i
fromIndex, inclusive and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of appl
to that element.

33) retainAll() It is used to retain only that element in the vector which is containe
collection.

34) set() It is used to replace the element at the specified position in the
specified element.

35) setElementAt() It is used to set the component at the specified index of the vecto
object.

36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the speci

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the
list.

40) subList() It is used to get a view of the portion of the list between fromInd
toIndex, exclusive.

41) toArray() It is used to get an array containing all of the elements in this vecto

42) toString() It is used to get a string representation of the vector.

43) trimToSize() It is used to trim the capacity of the vector to the vector's current si

Java Vector Example


import [Link].*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
[Link]("Tiger");
[Link]("Lion");
[Link]("Dmmm7mog");
[Link]("Elephant");
//Adding elements using addElement() method of Vector
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
[Link]("Elements are: "+vec);
}
}

Output:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains
insertion order.

However, there are many differences between ArrayList and Vector


classes that are given below.

ArrayList Vector

1) ArrayList is not Vector is synchronized.


synchronized.

2) ArrayList increments Vector increments 100% means doubles


50% of current array size the array size if the total number of
if the number of elements elements exceeds than its capacity.
exceeds from its capacity.

3) ArrayList is not a Vector is a legacy class.


legacy class. It is
introduced in JDK 1.2.

4) ArrayList Vector is slow because it is synchronized,


is fast because it is non- i.e., in a multithreading environment, it
synchronized. holds the other threads in runnable or non-
runnable state until current thread releases
the lock of the object.

5) ArrayList uses A Vector can use the Iterator interface


the Iterator interface to or Enumeration interface to traverse the
traverse the elements. elements.

You might also like