0% found this document useful (0 votes)
150 views

Java Unit-4

The document discusses the Java Collection framework which provides a unified architecture for storing and manipulating groups of objects. It describes key interfaces like Set, List, Queue, Map and classes like ArrayList, LinkedList. Generics are introduced to make collections type-safe by allowing only a specific type of object to be stored. The hierarchy of the Collection framework and commonly used List interface are also covered.

Uploaded by

Kondru Sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views

Java Unit-4

The document discusses the Java Collection framework which provides a unified architecture for storing and manipulating groups of objects. It describes key interfaces like Set, List, Queue, Map and classes like ArrayList, LinkedList. Generics are introduced to make collections type-safe by allowing only a specific type of object to be stored. The hierarchy of the Collection framework and commonly used List interface are also covered.

Uploaded by

Kondru Sirisha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit – 4 collection framework in java

4.0 Collections in Java


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
3. Java collection framework is a collection of interfaces and classes used to storing and
processing a group of individual objects as a single unit. The java collection framework
holds several classes that provide a large number of methods to store and process a
group of objects. These classes make the programmer task super easy and fast.
4. Java collection framework was introduced in java 1.2 version.

4.1 Generics in Java


The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes
the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now
generics force the java programmer to store a specific type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.

Without Generics, we can store any type of objects.

1. List list = new ArrayList();    
2. list.add(10);  
3. list.add("10");  
4. With Generics, it is required to specify the type of object we need to store.  
5. List<Integer> list = new ArrayList<Integer>();    
6. list.add(10);  
7. list.add("10");// compile-time error  

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

1. List list = new ArrayList();    
2. list.add("hello");    
3. String s = (String) list.get(0);//typecasting    
4. After Generics, we don't need to typecast the object.  
5. List<String> list = new ArrayList<String>();    
6. list.add("hello");    
7. String s = list.get(0);    

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.

1. List<String> list = new ArrayList<String>();    
2. list.add("hello");    
3. list.add(32);//Compile Time Error    

Syntax to use generic collection


1. ClassOrInterface<Type>    

Example to use Generics in java

1. ArrayList<String>    

Full Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;  
2. class TestGenerics1{  
3. public static void main(String args[]){  
4. ArrayList<String> list=new ArrayList<String>();  
5. list.add("rahul");  
6. list.add("jai");  
7. //list.add(32);//compile time error  
8.   
9. String s=list.get(1);//type casting is not required  
10. System.out.println("element is: "+s);  
11.   
12. Iterator<String> itr=list.iterator();  
13. while(itr.hasNext()){  
14. System.out.println(itr.next());  
15. }  
16. }  
17. }  

Output:

element is: jai


rahul
jai

4.2 Generic class


A class that can refer to any type is known as a generic class. Here, we are using the T type
parameter to create the generic class of specific type.
Let's see a simple example to create and use the generic class.

Creating a generic class:


1. class MyGen<T>{  
2. T obj;  
3. void add(T obj){this.obj=obj;}  
4. T get(){return obj;}  
5. }  

The T type indicates that it can refer to any type (like String, Integer, and Employee). The type
you specify for the class will be used to store and retrieve the data.

Using generic class:

Let's see the code to use the generic class.

1. class TestGenerics3{  
2. public static void main(String args[]){  
3. MyGen<Integer> m=new MyGen<Integer>();  
4. m.add(2);  
5. //m.add("vivek");//Compile time error  
6. System.out.println(m.get());  
7. }}  
Test it Now

Output

2
4.3 Collection interfaces or Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework. The java.util package contains all


the classes and interfaces for the Collection framework.
4.3.1 Collection interface methods

Sr.No Method & Description


.

1
boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was added to the collection.
Returns false if obj is already a member of the collection, or if the collection does
not allow duplicates.

2
boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the operation
succeeds (i.e., the elements were added). Otherwise, returns false.

3
void clear( )
Removes all elements from the invoking collection.

4
boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise, returns
false.

5
boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise,
returns false.

6
boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns false.

7
int hashCode( )
Returns the hash code for the invoking collection.

8
boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.

9
Iterator iterator( )
Returns an iterator for the invoking collection.

10
boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the
element was removed. Otherwise, returns false.

11
boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the
collection changed (i.e., elements were removed). Otherwise, returns false.

12
boolean retainAll(Collection c)
Removes all elements from the invoking collection except those in c. Returns true
if the collection changed (i.e., elements were removed). Otherwise, returns false.

13
int size( )
Returns the number of elements held in the invoking collection.

14
Object[ ] toArray( )
Returns an array that contains all the elements stored in the invoking collection.
The array elements are copies of the collection elements.

15
Object[ ] toArray(Object array[ ])
Returns an array containing only those collection elements whose type matches
that of array.

4.3.2 List Interface


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. It is a
factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and
backward directions. The implementation classes of List interface are ArrayList, LinkedList, Stack
and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class
is deprecated since Java 5.
List Interface declaration
1. public interface List<E> extends Collection<E>  

List Interface methods

Sr.No Method & Description


.

1
void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in the index. Any pre-existing
elements at or beyond the point of insertion are shifted up. Thus, no elements are
overwritten.

2
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the index. Any
pre-existing elements at or beyond the point of insertion are shifted up. Thus, no
elements are overwritten. Returns true if the invoking list changes and returns
false otherwise.

3
Object get(int index)
Returns the object stored at the specified index within the invoking collection.

4
int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not an
element of the list, .1 is returned.

5
int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not an
element of the list, .1 is returned.

6
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.

7
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.

8
Object remove(int index)
Removes the element at position index from the invoking list and returns the
deleted element. The resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one.

9
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.

10
List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list.
Elements in the returned list are also referenced by the invoking object.

4.3.3 Set interface in Java


The set is an interface available in the java.util package. The set interface extends the Collection
interface. An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface. The set interface is used to create the mathematical set. The set interface
use collection interface's methods to avoid the insertion of the same
elements. SortedSet and NavigableSet are two interfaces that extend the set implementation.

The methods declared by Set are summarized in the following table −

Sr.No Method & Description


.

1
add( )
Adds an object to the collection.

2
clear( )
Removes all objects from the collection.

3
contains( )
Returns true if a specified object is an element within the collection.
4
isEmpty( )
Returns true if the collection has no elements.

5
iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an
object.

6
remove( )
Removes a specified object from the collection.

7
size( )
Returns the number of elements in the collection.

4.4 commonly used collection classes :


4.5 ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array,


but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the java.util package. It is like
the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of List interface here. The ArrayList maintains
the insertion order internally.

It inherits the AbstractList class and implements List interface.

The important points about 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 array works at the index basis.
o In ArrayList, manipulation is 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.

Hierarchy of ArrayList class


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

ArrayList class declaration


Let's see the declaration for java.util.ArrayList class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAc
cess, Cloneable, Se

Java ArrayList Example


1. import java.util.*;  
2.  public class ArrayListExample1{  
3.  public static void main(String args[]){  
4.   ArrayList<String> list=new ArrayList<String>();//Creating arraylist    
5.       list.add("Mango");//Adding object in arraylist    
6.       list.add("Apple");    
7.       list.add("Banana");    
8.       list.add("Grapes");    
9.       //Printing the arraylist object   
10.       System.out.println(list);  
11.  }  
12. }  
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.

1. import java.util.*;  
2. public class ArrayListExample2{  
3.  public static void main(String args[]){  
4.   ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
5.   list.add("Mango");//Adding object in arraylist    
6.   list.add("Apple");    
7.   list.add("Banana");    
8.   list.add("Grapes");    
9.   //Traversing list through Iterator  
10.   Iterator itr=list.iterator();//getting the Iterator  
11.   while(itr.hasNext()){//check if iterator has the elements  
12.    System.out.println(itr.next());//printing the element and move to next  
13.   }  
14.  }  
15. }  
Test it Now

Output:

Mango
Apple
Banana
Grapes

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

1. import java.util.*;  
2. public class ArrayListExample3{  
3.  public static void main(String args[]){  
4.   ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
5.   list.add("Mango");//Adding object in arraylist    
6.   list.add("Apple");    
7.   list.add("Banana");    
8.   list.add("Grapes");    
9.   //Traversing list through for-each loop  
10.   for(String fruit:list)    
11.     System.out.println(fruit);    
12.   
13.  }  
14. }  

Output:

Test it Now

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.

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

Output:

Returning element: Apple


Mango
Dates
Banana
Grapes

How to Sort ArrayList


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

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

Output:

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

Ways to iterate the elements of the collection in Java


There are various ways to traverse the collection elements:

1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.

4.6 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 java.util 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 Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.

Java Vector class Declaration


1. public class Vector<E>  
2. extends Object<E>  
3. implements List<E>, Cloneable, Serializable  

NOTE: read only yellow color methods for vector class

Sr.No. Method & Description

1 void add(int index, Object element)


Inserts the specified element at the specified position in this Vector.

2 boolean add(Object o)
Appends the specified element to the end of this Vector.

3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector,
in the order that they are returned by the specified Collection's Iterator.

4 boolean addAll(int index, Collection c)


Inserts all of the elements in in the specified Collection into this Vector at the
specified position.

5 void addElement(Object obj)


Adds the specified component to the end of this vector, increasing its size by
one.

6 int capacity()
Returns the current capacity of this vector.

7 void clear()
Removes all of the elements from this vector.

8 Object clone()
Returns a clone of this vector.

9 boolean contains(Object elem)


Tests if the specified object is a component in this vector.

10 boolean containsAll(Collection c)
Returns true if this vector contains all of the elements in the specified
Collection.

11 void copyInto(Object[] anArray)


Copies the components of this vector into the specified array.
12 Object elementAt(int index)
Returns the component at the specified index.

13 Enumeration elements()
Returns an enumeration of the components of this vector.

14 void ensureCapacity(int minCapacity)


Increases the capacity of this vector, if necessary, to ensure that it can hold at
least the number of components specified by the minimum capacity argument.

15 boolean equals(Object o)
Compares the specified Object with this vector for equality.

16 Object firstElement()
Returns the first component (the item at index 0) of this vector.

17 Object get(int index)


Returns the element at the specified position in this vector.

18 int hashCode()
Returns the hash code value for this vector.

19 int indexOf(Object elem)


Searches for the first occurence of the given argument, testing for equality
using the equals method.

20 int indexOf(Object elem, int index)


Searches for the first occurence of the given argument, beginning the search at
index, and testing for equality using the equals method.

21 void insertElementAt(Object obj, int index)


Inserts the specified object as a component in this vector at the specified index.

22 boolean isEmpty()
Tests if this vector has no components.

23 Object lastElement()
Returns the last component of the vector.

24 int lastIndexOf(Object elem)


Returns the index of the last occurrence of the specified object in this vector.

25 int lastIndexOf(Object elem, int index)


Searches backwards for the specified object, starting from the specified index,
and returns an index to it.

26 Object remove(int index)


Removes the element at the specified position in this vector.

27 boolean remove(Object o)
Removes the first occurrence of the specified element in this vector, If the
vector does not contain the element, it is unchanged.

28 boolean removeAll(Collection c)
Removes from this vector all of its elements that are contained in the specified
Collection.

29 void removeAllElements()
Removes all components from this vector and sets its size to zero.

30 boolean removeElement(Object obj)


Removes the first (lowest-indexed) occurrence of the argument from this
vector.

31 void removeElementAt(int index)


removeElementAt(int index).

32 protected void removeRange(int fromIndex, int toIndex)


Removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.

33 boolean retainAll(Collection c)
Retains only the elements in this vector that are contained in the specified
Collection.

34 Object set(int index, Object element)


Replaces the element at the specified position in this vector with the specified
element.

35 void setElementAt(Object obj, int index)


Sets the component at the specified index of this vector to be the specified
object.

36 void setSize(int newSize)


Sets the size of this vector.

37 int size()
Returns the number of components in this vector.

38 List subList(int fromIndex, int toIndex)


Returns a view of the portion of this List between fromIndex, inclusive, and
toIndex, exclusive.

39 Object[] toArray()
Returns an array containing all of the elements in this vector in the correct
order.

40 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this vector in the correct
order; the runtime type of the returned array is that of the specified array.

41 String toString()
Returns a string representation of this vector, containing the String
representation of each element.

42 void trimToSize()
Trims the capacity of this vector to be the vector's current size.

Java Vector Example 3


1. import java.util.*;  
2. public class VectorExample2 {  
3.        public static void main(String args[]) {  
4.         //Create an empty Vector        
5.         Vector<Integer> in = new Vector<>();  
6.         //Add elements in the vector  
7.         in.add(100);  
8.         in.add(200);  
9.         in.add(300);  
10.         in.add(200);  
11.         in.add(400);  
12.         in.add(500);  
13.         in.add(600);  
14.         in.add(700);  
15.         //Display the vector elements  
16.         System.out.println("Values in vector: " +in);  
17.         //use remove() method to delete the first occurence of an element  
18.         System.out.println("Remove first occourence of element 200: "+in.remove((Inte
ger)200));  
19.         //Display the vector elements afre remove() method  
20.         System.out.println("Values in vector: " +in);  
21.         //Remove the element at index 4  
22.         System.out.println("Remove element at index 4: " +in.remove(4));  
23.         System.out.println("New Value list in vector: " +in);  
24.         //Remove an element  
25.         in.removeElementAt(5);        
26.         //Checking vector and displays the element  
27.         System.out.println("Vector element after removal: " +in);  
28.         //Get the hashcode for this vector  
29.         System.out.println("Hash code of this vector = "+in.hashCode());  
30.         //Get the element at specified index  
31.         System.out.println("Element at index 1 is = "+in.get(1));  
32.           }  
33. }  
Test it Now

Output:

Values in vector: [100, 200, 300, 200, 400, 500, 600, 700]
Remove first occourence of element 200: true
Values in vector: [100, 300, 200, 400, 500, 600, 700]
Remove element at index 4: 500
New Value list in vector: [100, 300, 200, 400, 600, 700]
Vector element after removal: [100, 300, 200, 400, 600]
Hash code of this vector = 130123751
Element at index 1 is = 300

4.7 Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a
key.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is
given below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap
and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null
key or value.

A Map can't be traversed, so you need to convert it into Set


using keySet() or entrySet() method.

Class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class.

It maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains

ascending order.
The java collection framework has an interface Map that is available inside
the java.util package. The Map interface is not a subtype of Collection interface.
🔔 The Map stores the elements as a pair of key and value.
🔔 The Map does not allows duplicate keys, but allows duplicate values.
🔔 In a Map, each key can map to at most one value only.
🔔 In a  Map, the order of elements depends on specific implementations, e.g
TreeMap and LinkedHashMap have predictable order, while HashMap does not.

Map methods

Sr.No. Method & Description

1 void clear( )
Removes all key/value pairs from the invoking map.

2 boolean containsKey(Object k)
Returns true if the invoking map contains k as a key. Otherwise, returns false.

3 boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise, returns false.

4 Set entrySet( )
Returns a Set that contains the entries in the map. The set contains objects of
type Map.Entry. This method provides a set-view of the invoking map.

5 boolean equals(Object obj)


Returns true if obj is a Map and contains the same entries. Otherwise, returns
false.
6 Object get(Object k)
Returns the value associated with the key k.

7 int hashCode( )
Returns the hash code for the invoking map.

8 boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise, returns false.

9 Set keySet( )
Returns a Set that contains the keys in the invoking map. This method provides
a set-view of the keys in the invoking map.

10 Object put(Object k, Object v)


Puts an entry in the invoking map, overwriting any previous value associated
with the key. The key and value are k and v, respectively. Returns null if the key
did not already exist. Otherwise, the previous value linked to the key is
returned.

11 void putAll(Map m)
Puts all the entries from m into this map.

12 Object remove(Object k)
Removes the entry whose key equals k.

13 int size( )
Returns the number of key/value pairs in the map.

14 Collection values( )
Returns a collection containing the values in the map. This method provides a
collection-view of the values in the map.
4.7.1 Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

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.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clo
neable, Serializab

Java Hashtable Example


1. import java.util.*;  
2. class Hashtable1{  
3.  public static void main(String args[]){  
4.   Hashtable<Integer,String> hm=new Hashtable<Integer,String>();  
5.   
6.   hm.put(100,"Amit");  
7.   hm.put(102,"Ravi");  
8.   hm.put(101,"Vijay");  
9.   hm.put(103,"Rahul");  
10.   
11.   for(Map.Entry m:hm.entrySet()){  
12.    System.out.println(m.getKey()+" "+m.getValue());  
13.   }  
14.  }  
15. }  
Test it Now

Output:

103 Rahul
102 Ravi
101 Vijay
100 Amit

Java Hashtable Example: remove()


1. import java.util.*;  
2. public class Hashtable2 {  
3.    public static void main(String args[]) {  
4.   Hashtable<Integer,String> map=new Hashtable<Integer,String>();        
5.      map.put(100,"Amit");    
6.      map.put(102,"Ravi");   
7.      map.put(101,"Vijay");    
8.      map.put(103,"Rahul");    
9.      System.out.println("Before remove: "+ map);    
10.        // Remove value for key 102  
11.        map.remove(102);  
12.        System.out.println("After remove: "+ map);  
13.    }      
14. }  

Output:

Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


After remove: {103=Rahul, 101=Vijay, 100=Amit}

Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class
have a quick view of how the stack works.

The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work on
stack.

Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

in java, the package java.util contains a class called Stack which is a child class of


Vector class. It implements the standard principle Last-In-First-Out of stack data
structure.
The Stack has push method for inesrtion and pop method for deletion. It also has
other utility methods.
🔔 In Stack, the elements are added to the top of the stack and removed from the
top of the stack.
The Stack class in java has the following constructor.

S. No. Constructor with Description

1 Stack( )

It creates an empty Stack.

The Stack class in java has the following methods.


S.No. Methods with Description

1 Object push(Object element)

It pushes the element onto the stack and returns the same.

2 Object pop( )
It returns the element on the top of the stack and removes the same.

3 int search(Object element)


If element found, it returns offset from the top. Otherwise, -1 is returned.

4 Object peek( )
It returns the element on the top of the stack.

5 boolean empty()
It returns true if the stack is empty, otherwise returns false.

1. import java.util.Stack;  
2. public class StackEmptyMethodExample  
3. {  
4. public static void main(String[] args)   
5. {  
6. //creating an instance of Stack class  
7. Stack<Integer> stk= new Stack<>();  
8. // checking stack is empty or not  
9. boolean result = stk.empty();  
10. System.out.println("Is the stack empty? " + result);  
11. // pushing elements into stack  
12. stk.push(78);  
13. stk.push(113);  
14. stk.push(90);  
15. stk.push(120);  
16. //prints elements of the stack  
17. System.out.println("Elements in Stack: " + stk);  
18. result = stk.empty();  
19. System.out.println("Is the stack empty? " + result);  
20. }  
21. }  

Output:

Is the stack empty? true


Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false

4.9 enumeration:
The enumeration() is a method of Java Collections class which is used to get the
enumeration over the specified collection.

Syntax
Following is the declaration of enumeration() method:

1. public static <T> Eenumeration<T> enumeration(Collection<T> c)  

Parameter
Parameter Description Required/Optiona

c It is a collections for which enumeration is to be returned. Required

Returns
The enumeration() method returns the enumeration over the specified collection.

1. import java.util.*;  
2. public class CollectionsEnumerationExample2 {  
3.     public static void main(String[] args) {  
4.         //Create array list object         
5.           List<Integer> Enum = new ArrayList<Integer>();                
6.             Enum.add(1100);  
7.             Enum.add(2100);  
8.             Enum.add(5100);  
9.             //Create Enumeration  
10.             Enumeration<Integer> en = Collections.enumeration(Enum);  
11.             System.out.println("The Enumeration List are: ");  
12.             while(en.hasMoreElements()){  
13.                  System.out.println(en.nextElement());  
14.             }          
15.     }       

4.10 Iterator interface


An iterator is an interface that is used in place of Enumerations in the Java Collection
Framework. Moreover, an iterator differs from the enumerations in two ways:

1. Iterator permits the caller to remove the given elements from the specified
collection during the iteration of the elements.
2. Method names have been enhanced.

Iterator interface is a member connected with Java Collections Framework.

Methods:
Methods Description

forEachRemaining(Consumer<? Performs the given action on each of the element until


super E>action)
and unless all the elements have been processed or unless
exception is thrown by the action.

hasNext() Returns a true value if the more number of elements

are encountered during iteration.


next() Returns the next specified element during the iteration.

remove() Removes the last element from the collection as

provided by the iterator.

Example 1
1. import java.util.Iterator;  
2. import java.util.LinkedList;  
3. import java.util.List;  
4. public class JavaIteratorExample1 {  
5.    public static void main(String[] args) {  
6.   List<String> list = new LinkedList<>();  
7.    list.add("Welcome");  
8.    list.add("to");  
9.    list.add("our");  
10.    list.add("website");  
11.     System.out.println("The list is given as : "+list);  
12.     Iterator<String> itr = list.iterator();  
13.        //Returns true if there are more number of elements.  
14.    while(itr.hasNext()) {  
15.        //Returns the next element.  
16.        System.out.println(itr.next());  
17.        }  
18.        //Removes the last element.  
19.    itr.remove();  
20.    System.out.println("After the remove() method is called : "+list);  
21.    }  
22. }  
Test it Now

Output:
The list is given as : [Welcome, to, our, website]
Welcome
to
our
website
After the remove() method is called : [Welcome, to, our]

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

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, String creates StringTokenizer with specified string and delimeter.
delim)

StringTokenizer(String str, String creates StringTokenizer with specified string, delimeter a


delim, boolean returnValue) returnValue. If return value is true, delimiter characters
considered to be tokens. If it is false, delimiter characters serve
separate tokens.

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:


Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class

Let's see the simple example of StringTokenizer class that tokenizes a string "my
name is khan" on the basis of whitespace.

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
Example of nextToken(String delim) method of
StringTokenizer class
1. import java.util.*;  
2.   
3. public class Test {  
4.    public static void main(String[] args) {  
5.        StringTokenizer st = new StringTokenizer("my,name,is,khan");  
6.         
7.       // printing next token  
8.       System.out.println("Next token is : " + st.nextToken(","));  
9.    }      
10. }  
Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split() method of String


class or regex (Regular Expression).

4.12 Random class


Java Random class is used to generate a stream of pseudorandom numbers. The
algorithms implemented by Random class use a protected utility method than can
supply up to 32 pseudorandomly generated bits on each invocation.

Methods
Methods Description

doubles() Returns an unlimited stream of pseudorandom double values.

ints() Returns an unlimited stream of pseudorandom int values.

longs() Returns an unlimited stream of pseudorandom long values.

next() Generates the next pseudorandom number.


nextBoolean() Returns the next uniformly distributed pseudorandom boolean value from

the random number generator's sequence

nextByte() Generates random bytes and puts them into a specified byte array.

nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0 from

the random number generator's sequence

nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0

and 1.0 from this random number generator's sequence

nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0 and

standard deviation 1.0 from this random number generator's sequence.

nextInt() Returns a uniformly distributed pseudorandom int value generated from

this random number generator's sequence

nextLong() Returns the next uniformly distributed pseudorandom long value from the rand
number generator's sequence.

setSeed() Sets the seed of this random number generator using a single long seed.

Example 1
1. import java.util.Random;  
2. public class JavaRandomExample1 {  
3.     public static void main(String[] args) {  
4.         //create random object  
5.         Random random= new Random();  
6.         //returns unlimited stream of pseudorandom long values  
7.             System.out.println("Longs value : "+random.longs());  
8.        // Returns the next pseudorandom boolean value  
9.         boolean val = random.nextBoolean();  
10.         System.out.println("Random boolean value : "+val);  
11.         byte[] bytes = new byte[10];  
12.         //generates random bytes and put them in an array  
13.         random.nextBytes(bytes);  
14.         System.out.print("Random bytes = ( ");  
15.         for(int i = 0; i< bytes.length; i++)  
16.         {  
17.             System.out.printf("%d ", bytes[i]);  
18.         }  
19.         System.out.print(")");  
20.     }  
21. }  
Test it Now

Output:

Longs value : java.util.stream.LongPipeline$Head@14ae5a5


Random boolean value : true
Random bytes = ( 57 77 8 67 -122 -71 -79 -62 53 19 )

4.13 scanner
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the java.util package.
The Scanner class implements Iterator interface.
The Scanner class provides the easiest way to read input in a Java program.
🔔 The Scanner object breaks its input into tokens using a delimiter pattern, the
default delimiter is whitespace.
The Scanner class in java has the following constructors.

S.No. Constructor with Description

1 Scanner(InputStream source)
S.No. Constructor with Description

It creates a new Scanner that produces values read from the specified input stream.

2 Scanner(InputStream source, String charsetName)


It creates a new Scanner that produces values read from the specified input stream.

3 Scanner(File source)
It creates a new Scanner that produces values scanned from the specified file.

4 Scanner(File source, String charsetName)


It creates a new Scanner that produces values scanned from the specified file.

5 Scanner(String source)
It creates a new Scanner that produces values scanned from the specified string.

6 Scanner(Readable source)
It creates a new Scanner that produces values scanned from the specified source.

7 Scanner(ReadableByteChannel source)
It creates a new Scanner that produces values scanned from the specified channel.

8 Scanner(ReadableByteChannel source, String charsetName)


It creates a new Scanner that produces values scanned from the specified channel.

The Scanner class in java has the following methods.

S.No. Methods with Description

1 String next()

It reads the next complete token from the invoking scanner.

2 String next(Pattern pattern)


It reads the next token if it matches the specified pattern.

3 String next(String pattern)


S.No. Methods with Description

It reads the next token if it matches the pattern constructed from the specified string.

4 boolean nextBoolean()
It reads a boolean value from the user.

5 byte nextByte()
It reads a byte value from the user.

6 double nextDouble()
It reads a double value from the user.

7 float nextFloat()
It reads a floating-point value from the user.

8 int nextInt()
It reads an integer value from the user.

9 long nextLong()
It reads a long value from the user.

10 short nextShort()
It reads a short value from the user.

11 String nextLine()
It reads a string value from the user.

12 boolean hasNext()
It returns true if the invoking scanner has another token in its input.

13 void remove()
It is used when remove operation is not supported by this implementation of Iterator.

14 void close()
It closes the invoking scanner.

Let's consider an example program to illustrate methods of Scanner class.


Example
import java.util.Scanner;

public class ScannerClassExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in); // Input stream is


used

System.out.print("Enter any name: ");


String name = read.next();

System.out.print("Enter your age in years: ");


int age = read.nextInt();

System.out.print("Enter your salary: ");


double salary = read.nextDouble();

System.out.print("Enter any message: ");


read = new Scanner(System.in);
String msg = read.nextLine();

System.out.println("\n------------------------------------------");
System.out.println("Hello, " + name);
System.out.println("You are " + age + " years old.");
System.out.println("You are earning Rs." + salary + " per
month.");
System.out.println("Words from " + name + " - " + msg);
}
}

Java Calendar Class


Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc. It inherits Object class and implements the Comparable interface.

Java Calendar class declaration


Let's see the declaration of java.util.Calendar class.

1. public abstract class Calendar extends Object   
2. implements Serializable, Cloneable, Comparable<Calendar>  

Java Calendar Class Example


1. import java.util.Calendar;  
2. public class CalendarExample1 {  
3.    public static void main(String[] args) {  
4.    Calendar calendar = Calendar.getInstance();  
5.    System.out.println("The current date is : " + calendar.getTime());  
6.    calendar.add(Calendar.DATE, -15);  
7.    System.out.println("15 days ago: " + calendar.getTime());  
8.    calendar.add(Calendar.MONTH, 4);  
9.    System.out.println("4 months later: " + calendar.getTime());  
10.    calendar.add(Calendar.YEAR, 2);  
11.    System.out.println("2 years later: " + calendar.getTime());  
12.    }  
13. }  
Test it Now

Output:

The current date is : Thu Jan 19 18:47:02 IST 2017


15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017
2 years later: Sat May 04 18:47:02 IST 2019

Properties class in Java


The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.

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.

An Advantage of the properties file


Recompilation is not required if the information is changed from a properties
file: If any information is changed from the properties file, you don't need to
recompile the java class. It is used to store information which is to be changed
frequently.

Example of Properties class to get information from the


properties file

To get information from the properties file, create the properties file first.

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.

You might also like