Collection Frame Work In Java
INTRODUCTION
Disadvantages:
To overcome this problem java introduces Collection Framework.
Collection FRAMEWORK
All Collections Frameworks Contain
Methods To Retrieve The Elements From The Collection Object Are
ForEach Group�
Ex: int a[]={1,2,3,4,5};
For Loop | ForEach Group |
Syntax: For(intialization;condition;increment/decrement) { } | Syntax: For(data_type variable:array_name) { } |
Ex: For(int i=0;i<a.lenth;i++) { System.out.println(a[i]); } | Ex: For(int x:a) { System.out.println(x); } |
Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
boolean hasMoreElements( )
It returns true, if enumaration contains the elements.
Object nextElement( )
It returns the next element available in the enumaration.
Note: this is applicable only legacy classes(Vector).
Ex:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements())
{
System.out.println(days.nextElement());
} } }
Iterator INTERFACE
Iterator hasNext()-> returns true if the iteration has more elements remaining in the collection.
Iterator next()->This method returns the next element in the iteration.
Iterator remove()-> it removes the last element.
Ex:
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
System.out.println(list);
Iterator<String> iterator = list.iterator();
while(iterator.hasNext())
{
String value = iterator.next();
System.out.println( value );
if(value.equals("B")) {
iterator.remove();
}
}
System.out.println(list);
} }
Output:
[A, B, C, D]
A
B
C
D
[A, C, D]
ListIterator
Methods In ListIterator Interface Are
Note: We can obtain the reference to list iterator for any given list using list.listIterator() method call.
ListIterator<T> listIterator = list.listIterator();
Method | Description |
hasNext() | Checks if there is a next element. |
next() | Returns the next element in the list. |
hasPrevious() | Checks if there is a previous element. |
previous() | Returns the previous element. |
remove() | Removes the last element returned by next() or previous(). |
add(Object o) | Adds a new element to the list. |
Ex
import java.io.*;
import java.util.*;
class Test {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
list.add("F");
ListIterator<String> listIterator = list.listIterator();
System.out.println("Forward iteration");
while(listIterator.hasNext()) {
System.out.print(listIterator.next() + ",");
}
System.out.println("Backward iteration");
while(listIterator.hasPrevious()) {
System.out.print(listIterator.previous() + ",");
}
System.out.println("Iteration from specified position");
listIterator = list.listIterator(2);
while(listIterator.hasNext()) {
System.out.print(listIterator.next() + ",");
} } }
Output:
Forward iteration
A,B,C,D,E,F,
Backward iteration
F,E,D,C,B,A,
Iteration from specified position
C,D,E,F,
��
List Interface
Vector
Method | Description |
add(E e) | Adds an element at the end of the vector. |
add(int index, E e) | Inserts an element at a specific position. |
remove(int index) | Removes element at the given index. |
get(int index) | Returns the element at the given index. |
size() | Returns number of elements in the vector. |
capacity() | Returns the current capacity of the vector. |
Ex:
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> v = new Vector<>();
v.add("Red");
v.add("Green");
v.add("Blue");
System.out.println("Vector elements: " + v);
System.out.println("Size: " + v.size());
System.out.println("Capacity: " + v.capacity());
}
}
Output:
Vector elements:
[Red, Green, Blue]
Size: 3Capacity: 10
ArrayList
Methods in ArrayList are:
Method | Description |
add(E e) | Adds element at the end of list. |
add(int index, E e) | Inserts element at specified position (middle possible). |
get(int index) | Returns element at specified index. |
set(int index, E e) | Replaces element at the given position. |
remove(int index) | Removes element at specified position. |
size() | Returns total number of elements. |
clear() | Removes all elements. |
Syntax: ArrayList<String> alist=new ArrayList<String>();
Ex :
import java.util.*;
class JavaExample
{
public static void main(String args[]){
ArrayList<String> alist=new ArrayList<String>();
alist.add("Steve");
alist.add("Tim");
alist.add("Lucy");
alist.add("Pat");
alist.add("Angela");
alist.add("Tom");
System.out.println(alist);
alist.remove("Steve");
alist.remove("Angela");
System.out.println(alist);
alist.remove(2);
System.out.println(alist);
}
}
Output:
[Steve, Tim, Lucy, Pat, Angela, Tom]
[Tim, Lucy, Pat, Tom]
[Tim, Lucy, Tom]
LinkedList
Methods in LinkedList are:
Syntax: LinkedList<String> alist=new LinkedList<String>();
Method | Description |
add(E e) | Adds an element at the end. |
addFirst(E e) | Adds an element at the beginning. |
addLast(E e) | Adds an element at the end (same as add). |
getFirst() | Returns the first element. |
getLast() | Returns the last element. |
removeFirst() | Removes the first element. |
removeLast() | Removes the last element. |
size() | Returns the number of elements. |
clear() | Removes all elements. |
Ex :
import java.util.*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> animals = new LinkedList<>();
animals.add("Dog"); animals.add("Cat"); animals.add("Cow"); animals.addFirst("Elephant"); animals.addLast("Tiger"); System.out.println("LinkedList: " + animals);
System.out.println("First Element: " + animals.getFirst()); System.out.println("Last Element: " + animals.getLast()); animals.removeFirst(); animals.removeLast();
System.out.println("After removing first and last: " + animals);
}
}
Output:
LinkedList:
[Elephant, Dog, Cat, Cow, Tiger]
First Element: Elephant
Last Element: Tiger
After removing first and last:
[Dog, Cat, Cow]
Stack
Methods in Stack are:
Method | Description |
push(E item) | Adds (pushes) an item onto the top of the stack. |
E pop() | Removes and returns the top item of the stack. |
E peek() | Looks at (but does not remove) the top item of the stack. |
boolean empty() | Checks if the stack is empty. |
int search(Object o) | Searches for an item and returns its 1-based position from the top if found, otherwise returns –1. |
Ex:
import java.util.Stack;
public class StackExample {
public static void main(String[] args)
{
Stack<String> stack = new Stack<>();
stack.push("Apple");
stack.push("Banana");
stack.push("Cherry");
System.out.println("Top element (peek): " + stack.peek()); System.out.println("Popped: " + stack.pop());
System.out.println("Is stack empty? " + stack.empty());
stack.pop();
stack.pop();
System.out.println("Is stack empty after popping all? " + stack.empty());
}
}
Top element (peek): Cherry
Popped: Cherry
Is stack empty? False
Is stack empty after popping all? true
QueueList
Common implementations:
LinkedList (most commonly used)
PriorityQueue (orders elements by priority)
Methods in QueueList are:
Method | Description |
add(E e) | Inserts the element into the queue; throws exception if full. |
offer(E e) | Inserts element; returns false if full (no exception). |
remove() | Removes and returns the head of the queue; throws exception if empty. |
poll() | Removes and returns head; returns null if empty. |
element() | Returns (but does not remove) the head element; throws exception if empty. |
peek() | Returns (but does not remove) head; returns null if empty. |
Ex:
import java.util.*;
public class QueueExample {
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");
queue.add("Task3");
System.out.println("Initial Queue: " + queue);
System.out.println("Head element (peek): " + queue.peek());
System.out.println("Removed: " + queue.remove()); System.out.println("Queue after removal: " + queue);
queue.offer("Task4");
System.out.println("After offer: " + queue);
queue.poll();
System.out.println("After poll: " + queue);
}}
Initial Queue: [Task1, Task2, Task3]
Head element (peek): Task1
Removed: Task1
Queue after removal: [Task2, Task3]
After offer: [Task2, Task3, Task4]
After poll: [Task3, Task4]
Hashmap
Method | Description |
put(K key, V value) | Inserts or updates a key–value pair. |
get(Object key) | Returns the value for the given key. |
remove(Object key) | Removes the entry for the given key. |
containsKey(Object key) | Checks if the key exists. |
containsValue(Object value) | Checks if a value exists. |
keySet() | Returns a set of all keys. |
values() | Returns a collection of all values. |
entrySet() | Returns a set of key–value pairs (Map.Entry objects). |
size() | Returns the number of key–value pairs. |
clear() | Removes all entries. |
Methods in Hashmap are:
Ex:
import java.util.*;
public class HashMapExample {
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");
System.out.println("HashMap: " + map);
System.out.println("Value for key 2: " + map.get(2));
map.remove(3);
System.out.println("Contains key 1? " + map.containsKey(1)); System.out.println("Contains value 'C++'? " + map.containsValue("C++"));
System.out.println("Keys: " + map.keySet()); System.out.println("Values: " + map.values());
}}
HashMap: {1=Java, 2=Python, 3=C++}
Value for key 2: Python
Contains key 1? True
Contains value 'C++'? False
Keys: [1, 2]
Values: [Java, Python]
String Tokenizer
Method | Description |
hasMoreTokens() | Checks if more tokens are available. |
nextToken() | Returns the next token (word). |
countTokens() | Returns how many tokens are left. |
Ex:
import java.util.*;
public class StringTokenizerExample {
public static void main(String[] args) {
String str = "Java,Python,C++,C";
StringTokenizer st = new StringTokenizer(str, ",");
System.out.println("Tokens are:");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}}
Tokens are:
Java
Python
C++
C