Java Unit-4
Java Unit-4
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:
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other 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
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
1. ArrayList<String>
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:
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.
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
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.
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>
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.
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.
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.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAc
cess, Cloneable, Se
Output:
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
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
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:
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
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.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a
collections framework.
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.
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.
10 boolean containsAll(Collection c)
Returns true if this vector contains all of the elements in the specified
Collection.
13 Enumeration elements()
Returns an enumeration of the components of this vector.
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.
18 int hashCode()
Returns the hash code value for this vector.
22 boolean isEmpty()
Tests if this vector has no components.
23 Object lastElement()
Returns the last component of the 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.
33 boolean retainAll(Collection c)
Retains only the elements in this vector that are contained in the specified
Collection.
37 int size()
Returns the number of components in this vector.
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.
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
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.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
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
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.
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.
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.
1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clo
neable, Serializab
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Output:
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.
1 Stack( )
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.
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:
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
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. }
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.
Methods:
Methods Description
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.
Constructor Description
StringTokenizer(String str, String creates StringTokenizer with specified string and delimeter.
delim)
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
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
Methods
Methods Description
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
nextFloat() Returns the next uniformly distributed pseudorandom Float value between 0.0
nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0 and
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:
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.
1 Scanner(InputStream source)
S.No. Constructor with Description
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.
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.
1 String next()
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.
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);
}
}
1. public abstract class Calendar extends Object
2. implements Serializable, Cloneable, Comparable<Calendar>
Output:
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.
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.