Collections in Java UNIT 4.1
Collections in Java UNIT 4.1
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).
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
Method Description
public boolean It is used to delete all the elements of the specified collection from
removeAll(Collection<?> c) the invoking collection.
default boolean It is used to delete all the elements of the collection that
removeIf(Predicate<? super satisfy the specified predicate.
E> filter)
public int size() It returns the total number of elements in the collection.
public void clear() It removes the total number of elements from the collection.
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.
There are only three methods in the Iterator interface. They are:
1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.
2 public Object next() It returns the element and moves the cursor pointer to
the next element.
3 public void remove() It removes the last elements returned by the 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.
Iterator<T> iterator()
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.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.
Constructor Description
Method Description
void add(int index, E It is used to insert the specified element at the specified position in a
element) list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean It is used to append all of the elements in the specified collection to the
addAll(Collection<? end of this list, in the order that they are returned by the specified
extends E> c) collection's iterator.
void It is used to sort the elements of the list on the basis of specified
sort(Comparator<? comparator.
super E> c)
int size() It is used to return the number of elements present in the list.
---------------------------------------------------------------------------------------------------------------------
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.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ravi
Ajay
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.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Output:
Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements
while traversing the list in the forward direction.
E next() This method returns the next element in the list and advances the
cursor position.
int nextIndex() This method returns the index of the element that would be returned
by a subsequent call to next()
boolean hasPrevious() This method returns true if this list iterator has more elements while
traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and moves the
cursor position backward.
E previousIndex() This method returns the index of the element that would be returned
by a subsequent call to previous().
void remove() This method removes the last element from the list that was returned
by next() or previous() methods
void set(E e) This method replaces the last element returned by next() or
previous() methods with the specified element.
Output:
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.
SN Constructor Description
3) HashSet(int capacity, float It is used to initialize the capacity of the hash set
loadFactor) to the given integer value capacity and the
specified load factor.
Constructor Description
TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the
elements of the collection c.
Method Description
boolean contains(Object o) It returns true if this set contains the specified element.
E first() It returns the first (lowest) element currently in this sorted set.
E last() It returns the last (highest) element currently in this sorted set.
1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element
is removed first and last element is removed at last.
Method Description
boolean add(object) It is used to insert the specified element into this queue and
return true upon success.
boolean offer(object) It is used to insert the specified element into this queue.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue,
or returns null if this queue is empty.
PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner. It inherits AbstractQueue class.
Method Description
boolean add(object) It is used to insert the specified element into this deque
and return true upon success.
boolean offer(object) It is used to insert the specified element into this deque.
Object remove() It is used to retrieves and removes the head of this deque.
Object poll() It is used to retrieves and removes the head of this deque,
or returns null if this deque is empty.
Object element() It is used to retrieves, but does not remove, the head of this deque.
Object peek() It is used to retrieves, but does not remove, the head of this deque,
or returns null if this deque is empty.
ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.
Output:
Ravi
Vijay
Ajay
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Methods of Java Comparator Interface
Method Description
public int compare(Object obj1, Object It compares the first object with the second object.
obj2)
public boolean equals(Object obj) It is used to compare the current object with
the specified object.
public boolean equals(Object obj) It is used to compare the current object with
the specified object.
Collections class
Collections class provides static methods for sorting the elements of a collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type
elements also.
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If the age of the first object is greater than
the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age of the
first object is less than the second object, we are returning a negative value, it can be any
negative value, and if the age of both objects is equal, we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the values of the object by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("Sorting by age");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27
This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.
1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
Simple.java
In this class, we are printing the values of the object by sorting on the basis of name and age.
1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("Sorting by age");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24. }
25. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27
It can be used to get property value based on the property key. The Properties class provides
methods to get data from the properties file and store data into the properties file. Moreover, it
can be used to get the properties of a system.
Method Description
Properties(Properties defaults) It creates an empty property list with the specified defaults.
Method Description
public void load(InputStream is) It loads data from the InputStream object
public String getProperty(String key, It searches for the property with the
String defaultValue) specified key.
public void setProperty(String key, It calls the put method of Hashtable.
String value)
public void list(PrintStream out) It is used to print the property list out to the specified
output stream.
public void list(PrintWriter out)) It is used to print the property list out to the specified
output stream.
public Set<String> It returns a set of keys in from property list where the
stringPropertyNames() key and its corresponding value are strings.
public void store(Writer w, String It writes the properties in the writer object.
comment)
public void store(OutputStream os, It writes the properties in the OutputStream object.
String comment)
public void storeToXML(Writer w, It writes the properties in the writer object for
String comment, String encoding) generating XML document with the specified encoding.
db.properties
1. user=system
2. password=oracle
Now, let's create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the java class.
That means no maintenance problem.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket
is identified by calling the hashcode() method. A Hashtable contains values based on the
key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Constructor Description
Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified i
loadFactor.
Hashtable(Map<? extends K,? extends It creates a new hash table with the same
V> t) mappings as the given Map.
Method Description
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super It performs the given action for each entry in the map until
K,? super V> action) all entries have been processed or the action throws an
exception.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
defaultValue) map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.
Set<K> keySet() It returns a Set view of the keys contained in the map.
V put(K key, V value) It inserts the specified value with the specified key in the
hash table.
void putAll(Map<? extends K,? It is used to copy all the key-value pair from map to
extends V> t)) hashtable.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified
newValue) key.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.
boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key
exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns
false if it contains at least one key.
int size() This method returns the number of entries in the hash
table.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Output:
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor Description
String nextToken(String delim) returns the next token based on the delimeter.
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan
StringTokenizer class is deprecated now. It is recommended to use split() method of String class
or regex (Regular Expression).
java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods
to deal with date and time in java.
After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.
java.util.Date Constructors
2) Date(long milliseconds) Creates a date object for the given milliseconds since January
1, 1970, 00:00:00 GMT.
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if current date is after the given date.
2) boolean before(Date date) tests if current date is before the given date.
5) boolean equals(Date date) compares current date with given date for equality.
6) static Date from(Instant returns an instance of Date object from Instant date.
instant)
8) int hashCode() returns the hash code value for this date object.
9) void setTime(long time) changes the current date and time to given time.
java.util.Date Example
Let's see the example to print date in java using java.util.Date class.
1st way:
Output:
2nd way:
1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Each component of bit set contains at least one Boolean value. The contents of one BitSet may be
changed by other BitSet using logical AND, logical OR and logical exclusive OR operations.
Each element of bits contains either true or false value. Initially, all bits of a set have the false
value. A BitSet is not safe for multithreaded use without using external synchronization.
Note: Passing a null parameter to any of the methods of BitSet class will throw a NullPointerException.
2 void andNot(BitSet set) This method is used to clear the entire bit
corresponding bit is set in the specified BitSet.
3 int cardinality() This method returns the number of b ts set to
4 void clear() This method set false to all bits in this BitSet.
6 void clear(int fromIndex, This method set bits to false from specified
int toIndex)
fromIndex (inclusive) to toIn ex (exclusive).
10 void flip(int fromIndex, This method set each bit value to its
int toIndex)
complement from specified fromIndex (i
(exclusive).
12 BitSet get(int fromIn ex, This method returns a new BitSet of bits
int toIndex)
from specified fromIndex (inclusive) to toInde
13 int hashCode() This method returns the hash co
e
set to true.
this BitSet.
specified argument.
20 int previousClearBit(int This method returns the index of the
fromIndex)
nearest bit which is set to false which
22 void set(int bitIndex) This method sets true to bit value at the
specified index.
24 void set(int fromIndex, This method sets the bits from specified
int toIndex)
fromIndex (inclusive) to toIndex (exclusive) to
25 void set(int fromIndex, This method sets the bits from specified
int toIndex, b olean
fromIndex (inclusive) to toIndex
value)
(exclusive) to specified boolean value.
31 static BitSet valueOf(byte[] This method returns a new bit set of the
bytes)
given byte array.
33 static BitSet valueOf(ByteBuffer This method returns a new bit set from
bb)
the given byte buffer.
34 static BitSet valueOf(LongBuffer This method returns a new bit set from
lb)
the given long buffer.
No Method Description
1. public void add(int field, int Adds the specified (signed) amount of time
amount)
to the given calendar field.
2. public boolean after (Object when) The method Returns true if the time represented
when Object.
3. public boolean before(Object The method Returns true if the time represented
when)
by this Calendar is before the time represented by
when Object.
4. public final void clear(int field) Set the given calendar field value and the time
5. public Object clone() Clone method provides the copy of the current
object.
7. protected void complete() It fills any unset fields in the calendar fields.
8. protected abstract void It converts the current millisecond time value
computeFields()
time to calendar field values in fields[].
10. public boolean equals(Object The equals() method compares two objects for
object)
equality and Returns true if they are equal.
11. public int get(int field) In get() method fields of the calendar are passed
12. public int getActualMaximum(int Returns the Maximum possible value of the calendar f
field) parameter to getActualMaximum() method.
13. public int getActualMinimum(int Returns the Minimum possible value of the
field)
calendar field passed as parameter to
getActualMinimum() methot.
14. public static Set<String> Returns a set which contains string set of
getAvailableCalendarTypes()
all available calendar type supported by Java
Runtime Environment.
15. public static Locale[] Returns an array of all locales available in java
getAvailableLocales()
runtime environment.
16. public String getCalendarType() Returns in string all available calendar type
17. public String getDisplayName(int Returns the String representation of the calendar
field, int style, Locale locale)
field value passed as the parameter in a given
local.
19. public int getFirstDayOfWeek() Returns the first day of the week in integer form.
20. public abstract int This method returns the highest minimum value of
getGreatestMinimum(int field)
Calendar field passed as the parameter.
21. public static Calendar This method is used with calendar object to get the
getInstance()
instance of calendar according to current time zone
22. public abstract int Returns smallest value from all maximum value for
getLeastMaximum(int field)
the field specified as the parameter to the method.
23. public abstract int getMaximum(int This method is used with calendar object to get the
field)
maximum value of the specified calendar field as the pa
25. public abstract int getMinimum(int This method is used with calendar object to get the
field) specified calendar field as the parameter.
26. public final Date getTime() This method gets the time value of calendar object
27. public long getTimeInMillis() Returns the current time in millisecond. This method
type.
28. public TimeZone getTimeZone() This method gets the TimeZone of calendar
29. public int getWeeksInWeekYear() Return total weeks in week year. Weeks in
30. public int getWeekYear() This method gets the week year represented by
current Calendar.
31. public int hashCode() All other classes in Java overload hasCode() method.
object.
32. protected final int internalGet(int This method returns the value of the calendar
field)
field passed as the parameter.
33. Public boolean isLenient() Return Boolean value. True if the interpretation
mode of this calendar is lenient; false otherwise.
34. public final boolean isSet(int field) This method checks if specified field as the
36. public abstract void roll(int field, This method increase or decrease the specified
boolean up)
calendar field by one unit without affecting the
other field
37. public void set(int field, int value) Sets the specified calendar field by the specified
value.
38. public void setFirstDayOfWeek(int Sets the first day of the week. The value which is to
value)
be set as the first day of the week is passed as
parameter.
39. public void Sets the minimal days required in the first week.
setMinimalDaysInFirstWeek(int
The value which is to be set as minimal days in
value)
40. public final void setTime(Date Sets the Time of current calendar object.
date)
A Date object id passed as the parameter.
41. public void setTimeInMillis(long Sets the current time in millisecond.
millis)
42. public void setTimeZone(TimeZone Sets the TimeZone with passed TimeZone
value)
value (object) as the parameter.
43. public void setWeekDate(int Sets the current date with specified integer value
weekYear, int weekOfYear, int
as the parameter. These values are weekYear,
dayOfWeek)
dayOfWeek.
44. public final Instant toInstant() The toInstant() method convert the current object
to an instant.
45. public String toString() Returns string representation of the current object.
Vector is very useful if we don't know the size of an array in advance or we need one that can
change the size over the lifetime of a program.
Vector implements a dynamic array that means it can grow or shrink as required. It is similar to
the ArrayList, but with two differences-
o Vector is synchronized.
o The vector contains many legacy methods that are not the part of a collections framework
Vector Declaration:
1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
Java Vector Class Constructors
Vector class supports four types of constructors. These are:
SN Constructor Description
8) containsAll() It returns true if the vector contains all of the elements in the
specified collection.
13) equals() It is used to compare the specified object with the vector for
equality.
15) forEach() It is used to perform the given action for each element of the
Iterable until all 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.
18) indexOf() It is used to get the index of the first occurrence of the specified
element in the 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 given
vector at the specified index.
21) iterator() It is used to get an iterator over the elements in the list in proper
sequence.
23) lastIndexOf() It is used to get the index of the last occurrence of the
specified element in the 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
sequence.
25) remove() It is used to remove the specified element from the vector. If the
vector does not contain the element, it is unchanged.
26) set() It is used to replace the element at the specified position in the
vector with the specified element.
27) setElementAt() It is used to set the component at the specified index of the vector
to the specified object.
29) size() It is used to get the number of components in the given vector.
30) sort() It is used to sort the list according to the order induced by the
specified Comparator.
32) subList() It is used to get a view of the portion of the list between fromIndex,
inclusive, and toIndex, exclusive.
33) toArray() It is used to get an array containing all of the elements in this
vector in correct order.
35) trimToSize() It is used to trim the capacity of the vector to the vector's
current size.
Example:
1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer