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

Module 1 - Collections Framework

The document provides an overview of the Java Collections Framework, detailing its architecture, interfaces, and classes used for storing and manipulating groups of objects. It covers key interfaces such as List, Set, Queue, and Map, along with their methods and functionalities. Additionally, it discusses the benefits of using the framework, including type-safety and improved performance, as well as examples of how to implement and use these collections in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Module 1 - Collections Framework

The document provides an overview of the Java Collections Framework, detailing its architecture, interfaces, and classes used for storing and manipulating groups of objects. It covers key interfaces such as List, Set, Queue, and Map, along with their methods and functionalities. Additionally, it discusses the benefits of using the framework, including type-safety and improved performance, as well as examples of how to implement and use these collections in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 102

ADVANCED JAVA-

BCS402
The collections and Framework: Collections
Overview, The Collection Interfaces, The Collection
Classes, accessing a collection Via an Iterator, Storing
User Defined Classes in Collections, The Random
Access, Interface, Working with Maps, Comparators,
The Collection Algorithms, Arrays, The legacy Classes
and Interfaces, Parting Thoughts on Collections
Collection 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 sear
• Java Collection framework provides many interfaces such as
• Set, List, Queue, Deque
• classes
• ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
• Searching, sorting, insertion, manipulation, and deletion.
Collection in Java
• What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Collection framework

• The Collections Framework is a fundamental part of the Java API,


providing a set of interfaces and classes to represent and manipulate
collections of objects. The framework provides a standardized
architecture for storing and manipulating groups of objects, making it
easier to work with data in various forms. Here's a brief overview:
• Interfaces: The Collections Framework includes several core
interfaces such as List, Set, Queue, and Map. These interfaces define
common behaviors and operations for working with collections.
• Classes: There are various classes in the framework that implement
these interfaces. Some common examples include ArrayList,
LinkedList, HashSet, TreeSet, HashMap, TreeMap, and LinkedList.
Collection framework
• Algorithms: The framework also includes algorithms for operations
like sorting, searching, and shuffling collections. These algorithms are
defined as static methods in the Collections class.
• Benefits: The Collections Framework provides several benefits,
including reusability, type-safety, interoperability, and improved
performance. By using the framework, developers can write code that
is more concise, efficient, and easier to maintain.
• Generics: With the introduction of generics in Java 5, the Collections
Framework became even more powerful and type-safe. Generics
allow developers to specify the type of objects that a collection can
contain, providing compile-time type checking and reducing the risk
of runtime errors.
Java Collections Framework
• The Java collections framework provides a set of interfaces and
classes to implement various data structures and algorithms.
• Interfaces of Collections Frameworks
Java Collection Interface

The Collection interface is the root interface of the Java


collections framework.

There is no direct implementation of this interface.


However, it is implemented through its sub interfaces
like List, Set and Queue.
Methods in Collection Interface
•add() - inserts the specified element to the collection
•size() - returns the size of the collection
•remove() - removes the specified element from the collection
•iterator() - returns an iterator to access elements of the collection
•addAll() - adds all the elements of a specified collection to the
collection
•removeAll() - removes all the elements of the specified collection from
the collection
•clear() - removes all the elements of the collection
Collection Interfaces - List
List is an interface is an ordered collection that allows us to store and access elements sequentially.
It extends the Collection Interface.
Since List is an interface users cannot create Objects from it.
Creation of Linked List
//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();

//Creating a List of type Integer using ArrayList


List<Integer> list=new ArrayList<Integer>();

//Creating a List of type Book using ArrayList


List<Book> list=new ArrayList<Book>();

//Creating a List of type String using LinkedList


List<String> list=new LinkedList<String>();
List example
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Collection Interfaces - Set
• The Set interface defines a set.
• It extends Collection and specifies the behavior of a collection that
does not allow duplicate elements.
• Set is a generic interface that has this declaration: interface Set<E>
• Here, E specifies the type of objects that the set will hold.
Collection Interface - Sorted set
The SortedSet interface of the Java collections framework is used to
store elements with some order in a set.
It extends the Set interface.
Methods in Set Interface
add() - adds the specified element to the set
addAll() - adds all the elements of the specified collection to the set
iterator() - returns an iterator that can be used to access elements of the set
sequentially
remove() - removes the specified element from the set
removeAll() - removes all the elements from the set that is present in another
specified set
retainAll() - retains all the elements in the set that are also present in another
specified set
clear() - removes all the elements from the set
size() - returns the length (number of elements) of the set
toArray() - returns an array containing all the elements of the set
contains() - returns true if the set contains the specified element
containsAll() - returns true if the set contains all the elements of the specified
collection
hashCode() - returns a hash code value (address of the element in the set)
Interface – SortedSet
• SortedSet interface present in java.util package extends the Set interface
present in the collection framework.
• It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Set interface and adds a
feature that stores all the elements in this interface to be stored in a
sorted manner.

• The class which implements the navigable set is a TreeSet which is an


implementation of a self-balancing tree. Therefore, this interface
provides us with a way to navigate through this tree.
Methods in sorted set

1. boolean add(E lement)


E- type of the element maintained by this Set
The add() method of SortedSet in Java is used to add a specific element
into a Set collection. The function adds the element only if the specified
element is not already present in the set else the function returns False
if the element is already present in the Set.
Example :
SortedSet<Integer> s = new TreeSet<Integer>();
s.add(10);
s.add(20);
boolean addAll(Collection c)
The addAll(Collection C) method is used to append all of the elements
from the mentioned collection to the existing set.
The elements are added randomly without following any specific order.
boolean void addAll(Collections C)
Parameters: The parameter C is a collection of any type that is to be
added to the set.
Return Value: The method returns true if it successfully appends the
elements of the collection C to this Set otherwise it returns False.
boolean containsAll(Collection c)
The containsAll() method of Java SortedSet is used to check whether
two sets contain the same elements or not. It takes one set as a
parameter and returns True if all of the elements of this set is present
in the other set.
Parameters: The parameter C is a Collection. This parameter refers to
the set whose elements occurrence is needed to be checked in this set.
Return Value: The method returns True if this set contains all the
elements of other set otherwise it returns False.
E first()
• The first() method of SortedSet interface in Java is used to Returns the
first i.e., the lowest element currently in this set.
• Where, E is the type of element maintained by this Set.
Parameters: This function does not accepts any parameter.
Return Value: It returns the first or the lowest element currently in
the set.
Exceptions: It throws NoSuchElementException, if the set is empty.
Below programs illustrate the above method:
Methods in SortedSet
Methods of SortedSet
The SortedSet interface includes all the methods of the Set
interface. It's because Set is a super interface of SortedSet.
Besides methods included in the Set interface,
the SortedSet interface also includes these methods:
1. comparator() - returns a comparator that can be used to
order elements in the set
2. first() - returns the first element of the set
3. last() - returns the last element of the set
4. headSet(element) - returns all the elements of the set
before the specified element
5. tailSet(element) - returns all the elements of the set after
the specified element including the specified element
6. subSet(element1, element2) - returns all the elements
between the element1 and element2 including element1
Collection Interfaces – Queue.
• Working of Queue Data Structure
• In queues, elements are stored and accessed in First In, First
Out manner. That is, elements are added from the
behind and removed from the front.
Methods of Queue

The Queue interface includes all the methods of


the Collection interface. It is because Collection is the super
interface of Queue.
Some of the commonly used methods of the Queue interface are:
•add() - Inserts the specified element into the queue. If the task is
successful, add() returns true, if not it throws an exception.
•offer() - Inserts the specified element into the queue. If the task is
successful, offer() returns true, if not it returns false.
•element() - Returns the head of the queue. Throws an exception if
the queue is empty.
•peek() - Returns the head of the queue. Returns null if the queue is
empty.
•remove() - Returns and removes the head of the queue. Throws an
exception if the queue is empty.
•poll() - Returns and removes the head of the queue. Returns null if
Deque – Double ended queue
The Deque interface extends Queue and declares the behavior of a
double-ended queue.
Double-ended queues can function as standard, first-in, first-out
queues
Generic interface that has this declaration:
interface Deque<E>
E – type of object that Queue holds
Deeque -

Operations performed on deque


1. Insertion at front
2. Insertion at rear
3. Deletion at front
4. Deletion at rear
5. Get the front item from the deque
6. Get the rear item from the deque
7. Check whether the deque is full or not
8. Checks whether the deque is empty or not
Methods in Deque
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 retrieve and removes the head of this deque.
Object poll()
It is used to retrieve and removes the head of this deque, or returns
null if this deque is empty.
Methods in Deque
Object element()
It is used to retrieve, but does not remove, the head of this deque.
Object peek()
It is used to retrieve, but does not remove, the head of this deque, or
returns null if this deque is empty.
Object offerLast(e)
Inserts the element e at the tail of the queue. If the insertion is
successful, true is returned; otherwise, false.
Methods in Deque
Object peekFirst()
The method returns the head element of the deque. The method does
not remove any element from the deque. Null is returned by this
method, when the deque is empty.
Object peekLast()
The method returns the last element of the deque. The method does
not remove any element from the deque. Null is returned by this
method, when the deque is empty.
boolean offerFirst(e)
Inserts the element e at the front of the queue. If the insertion is
successful, true is returned; otherwise, false.
Collection framework – Map
interface
• Map Interface is present in java.util package represents a mapping
between a key and a value.
• Java Map interface is not a subtype of the Collection interface.
Therefore it behaves a bit differently from the rest of the collection
types.
• A map contains unique keys.
Map Interface
Methods in Map Interface
V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in


the map.

V putIfAbsent(K key, V value) It inserts the specified value with the


specified key in the map only if it is not
already specified.

V remove(Object key) It is used to delete an entry for the specified


key.

boolean remove(Object key, Object value) It removes the specified values with the
associated specified keys from the map.
Methods in Map Interface
Set keySet() It returns the Set view containing
all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing
all the keys and values.
void clear() It is used to reset the map.
boolean containsValue(Object value) This method returns true if some
value equal to the value exists within
the map, else return false.
boolean containsKey(Object key) This method returns true if some key
equal to the key exists within the
map, else return false.
boolean equals(Object o) It is used to compare the specified
Object with the Map.
int hashCode() It returns the hash code value for the
Map
boolean isEmpty() This method returns true if the map
is empty; returns false if it contains
at least one key.
Map Interface
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
//Elements can traverse in any order
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
SortedMap - Interface
SortedMap - Interface
• The main characteristic of a SortedMap is that it orders the keys by
their natural ordering, or by a specified comparator. So consider using
a TreeMap when you want a map that satisfies the following criteria:
• null key or null value is not permitted.
• The keys are sorted either by natural ordering or by a specified
comparator
• The main difference between a SortedMap and a regular Map is that
the elements in a SortedMap are stored in a sorted order, whereas in
a Map the elements are stored in an arbitrary order.
.
SortedMap - Interface
• Since SortedMap is an interface, it can be used only with a class that
implements this interface.
• TreeMap is the class that implements the SortedMap interface. Now,
let’s see how to perform a few frequently used operations on the
TreeMap.
Syntax:
• SortedMap<Obj1, Obj2> set = new TreeMap<Obj1, Obj2> ();
Methods in Sorted Map
Comparator Interface
Java Comparator interface is used to order the objects of a user-
defined class.
Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared.
Methods of Java Comparator Interface (before
jdk 8.0)
Methods of Comparator (after jdk 8.)
Example of sorting the elements of List on the basis of age
and name.
public int getRollno() {
class Student {
return rollno;
int rollno;
}
String name;
int age; public void setRollno(int rollno) {
Student(int rollno,String name,int a this.rollno = rollno;
ge){
}
this.rollno=rollno;
this.name=name; public String getName() {
this.age=age; return name;
} }
Example of sorting the elements of List on the basis of age
and name.
/
import java.util.*; Sorting elements on the basis of na
public class TestSort1{ me
public static void main(String args[]) Comparator<Student> cm1=Comp
{ arator.comparing(Student::getNam
e);
ArrayList<Student> al=new ArrayList
<Student>(); Collections.sort(al,cm1);
System.out.println("Sorting by Na
al.add(new Student(101,"Vijay",23)) me");
;
for(Student st: al){
al.add(new Student(106,"Ajay",27));
System.out.println(st.rollno+" "+
st.name+" "+st.age);
al.add(new Student(105,"Jai",21)); }
Example of sorting the elements of List
on the basis of age and name.
//Sorting elements on the basis of age
Comparator<Student> cm2=Comparator
.comparing(Student::getAge);
Collections.sort(al,cm2);
System.out.println("Sorting by Age");
for(Student st: al){
System.out.println(st.rollno+" "+st.nam
e+" "+st.age);
}
}
}
Iterator Interface
The Java Iterator is an interface added in the Java Programming language
in the Java 1.2 Collection framework. It belongs to java.util package.
It is one of the Java Cursors that are practiced to traverse the objects of
the collection framework.
The Java Iterator is used to iterate the components of the collection
object one by one.
The Java Iterator is also known as the Universal cursor of Java as it is
appropriate for all the classes of the Collection framework.
The Java Iterator also supports the operations like READ and REMOVE.
The methods names of the Iterator class are very simple and easy to use
compared to the method names of Enumeration Iterator.
Java Iterator Methods

• The following figure perfectly displays the class diagram of the Java
Iterator interface. It contains a total of four methods that are:
hasNext()
next()
remove()
forEachRemaining()
Methods in Iterator Interface
boolean hasNext():
• The method does not accept any parameter. It returns true if there
are more elements left in the iteration.
• If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no
need to call the next() method.
E next():
• It is similar to hasNext() method. It also does not accept any
parameter. It returns E, i.e., the next element in the traversal.
• If the iteration or collection of objects has no more elements left to
iterate, then it throws the NoSuchElementException.
Methods in Iterator Interface
void remove():
• This method also does not require any parameters.
• There is no return type of this method. The main function of this method
is to remove the last element returned by the iterator traversing t
void forEachRemaining(Consumer action): It is the only method of Java
Iterator that takes a parameter.
• It accepts action as a parameter. Action is nothing but that is to be
performed.
• There is no return type of the method. This method performs the
particularized operation on all of the left components of the collection
until all the components are consumed or the action throws an exception
JavaIteratorExample.java
import java.io.*; // Iterator to iterate the cityNames
import java.util.*; Iterator iterator = cityNames.iterator()
;
public class JavaIteratorExample {
public static void main(String[] args)
System.out.println("CityNames eleme
{ nts : ");
ArrayList<String> cityNames = new A
rrayList<String>(); while (iterator.hasNext())
cityNames.add("Delhi"); System.out.print(iterator.next() + " "
cityNames.add("Mumbai"); );

cityNames.add("Kolkata");
System.out.println();
cityNames.add("Chandigarh");
}
cityNames.add("Noida");
Collection Framework – Collection
Classes
Array List
• Java ArrayList class uses a dynamic array for storing
the elements. It is like an array, but there is no size
limit.
• User can add or remove elements anytime. So, it is
much more flexible than the traditional array.
• The ArrayList in Java can have the duplicate elements
also. It implements the List interface so we can use all
the methods of the List interface here. The ArrayList
maintains the insertion order internally.
• It inherits the AbstractList class and implements
List interface.
Characteristics of an ArrayList Class
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because the array works on an index basis.
• In ArrayList, manipulation is a little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from the
array list.
• We can not create an array list of the primitive types, such as int, float, char,
etc. It is required to use the required wrapper class in such cases. For example:
• ArrayList<int> al = ArrayList<int>(); // does not work
• ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
Methods in Array List
Methods in Array List
Iterating Array List using Iterator
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Linked List class
• Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class
and implements List and Deque interfaces.
Characteristics of Linked List class
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs
to occur.
• Java LinkedList class can be used as a list, stack or queue.
Methods in Linked List
Collection Class – Hashset
• HashSet stores the elements by using a
mechanism called hashing.
• HashSet contains unique elements
only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion
order. Here, elements are inserted on
the basis of their hashcode.
• HashSet is the best approach for
search operations.
Methods in Hashset
1.boolean contain(Object obj)
It is used to return true if this set contains the specified element.
2.Boolean isEmpty()
3.boolean remove(Object obj)
4.int size()
Example
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Java HashSet from another Collection

import java.util.*;
class HashSet4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ajay");

HashSet<String> set=new HashSet(list);


set.add("Gaurav");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Treeset class
• Java TreeSet class implements
the Set interface that uses a tree
for storage. It inherits
AbstractSet class and
implements the NavigableSet
interface. The objects of the
TreeSet class are stored in
ascending order.
• The important points about the
Java TreeSet class are:
Characteristics of Treeset class

• Java TreeSet class contains unique elements only like HashSet.


• Java TreeSet class access and retrieval times are quiet fast.
• Java TreeSet class doesn't allow null element.
• Java TreeSet class is non synchronized.
• Java TreeSet class maintains ascending order.
• The TreeSet can only allow those generic types that are comparable.
For example The Comparable interface is being implemented by the
StringBuffer class.
Legacy Class in Java

• In the past decade, the Collection framework didn't include in Java. In


the early version of Java, we have several classes and interfaces which
allow us to store objects.
• After adding the Collection framework in JSE 1.2, for supporting the
collections framework, these classes were re-engineered. So, classes
and interfaces that formed the collections framework in the older
version of Java are known as Legacy classes.
• For supporting generic in JDK5, these classes were re-engineered.
• All the legacy classes are synchronized. The java.util package defines
the following legacy classes:
Legacy Class in Java

1. HashTable
2. Stack
3. Dictionary
4. Properties
5. Vector
Enumeraton Interface
HashTable
• Hashtable Class
• The Hashtable class is similar to HashMap. It also contains the data
into key/value pairs.
• It doesn't allow to enter any null key and value because it is
synchronized. Just like Vector, Hashtable also has the following four
constructors.
HashTable Methods
HashTable Methods
Hashtable Example

import java.util.*;
student.put(new Integer(104), "Ally");
class HashtableExample
Set dataset = student.entrySet();
{
Iterator iterate = dataset.iterator();
public static void main(String args[])
while(iterate.hasNext())
{
{
Hashtable<Integer,String> student = ne
w Hashtable<Integer, String>(); Map.Entry map=(Map.Entry)iterate.nex
t();
student.put(new Integer(101), "Emma")
; System.out.println(map.getKey()
+" "+map.getValue());
student.put(new Integer(102), "Adele");
}
student.put(new Integer(103), "Aria"); }
}
Properties – Legacy classes
Properties class methods
Example
prop_data.put("China", "CO2 Emissions
import java.util.*; and Renewable Energy.");
public class PropertiesExample prop_data.put("Sri Lanka", "Cinnamon.
{ ");
public static void main(String[] args) Set< ?
{ > set_data = prop_data.keySet();
Properties prop_data = new Properties(); for(Object obj: set_data)
prop_data.put("India", "Movies."); {
prop_data.put("United State", "Nobel Laur System.out.println(obj+" is famous fo
eates and Getting Killed by Lawnmowers."); r "+ prop_data.getProperty((String)obj));
prop_data.put("Pakistan", "Field Hockey."); }
}
}
Vector Class

• Vector is a special type of ArrayList that defines a dynamic array.


ArrayList is not synchronized while vector is synchronized.
• The vector class has several legacy methods that are not present in
the collection framework.
• Vector implements Iterable after the release of JDK 5 that defines the
vector is fully compatible with collections, and vector elements can be
iterated by the for-each loop.
Vector Constructors
1) Vector()
It is used when we want to create a default vector having the initial size of 10.
2) Vector(int size)
It is used to create a vector of specified capacity. It accepts size as a parameter to
specify the initial capacity.
3) Vector(int size, int incr)
It is used to create a vector of specified capacity. It accepts two parameters size
and increment parameters to specify the initial capacity and the number of
elements to allocate each time when a vector is resized for the addition of objects.
4) Vector(Collection c)
It is used to create a vector with the same elements which are present in the
collection. It accepts the collection as a parameter.
Vector class methods
Vector example
vec.add("Aidan");
import java.util.*; vec.add("Adriana");
public class VectorExample vec.add("Ally");
{ Enumeration<String> data = vec.el
public static void main(String[] args) ements();
{ while(data.hasMoreElements())
Vector<String> vec = new Vector<Str {
ing>(); System.out.println(data.nextElement()
vec.add("Emma"); );
vec.add("Adele"); }
vec.add("Aria"); }
}
Stack class
Stack Class –Methods
Stack class example
import java.util.*; while(enum1.hasMoreElements())
class StackExample {
public static void main(String args[]) { System.out.print(enum1.nextElement()+" ");
stack.pop();
Stack stack = new Stack(); stack.pop();
stack.push(“James"); stack.pop();
stack.push("Adele");
System.out.println("\
stack.push("Aria"); nAfter removing three elements from stack");
stack.push("Ally"); Enumeration enum2 = stack.elements();
stack.push("Paul"); while(enum2.hasMoreElements())
Enumeration enum1 = stack.el System.out.print(enum2.nextElement()+" ");
ements(); }
}
Dictionary class Methods
Dictionary
import java.util.Dictionary;
class Methods
import java.util.Enumeration; dict.remove("Alice");
import java.util.Hashtable;
public class DictionaryExample { System.out.println(dict.size()); // 2
public static void main(String[] args)
{ Enumeration<String> k = dict.keys();
Dictionary<String, Integer> dict= new while (k.hasMoreElements()) {
Hashtable<>();
dict.put("Alice", 25); String key = k.nextElement();
dict.put("Bob", 30); System.out.println("Key: " + key + ",
Value: "
dict.put("Charlie", 35);
+ dict.get(key));
System.out.println(dict.get("Bob")); // 30 }
}
int oldValue = dict.put("Charlie", 40); }
System.out.println(oldValue); // 35
Collection Algorithms
• The Collections Framework defines several algorithms that can be
applied to collections and maps. These algorithms are defined as
static methods within the Collections class.
• Collections defines three static variables: EMPTY_SET, EMPTY_LIST,
and EMPTY_MAP.
Example
// Demonstrate various algorithms.
import java.util.*;
class AlgorithmsDemo {
public static void main(String args[]) {
// Create and initialize linked list.
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
// Create a reverse order comparator.
Comparator<Integer> r = Collections.reverseOrder();
// Display randomized list.
Example System.out.print("List shuffled: ");
// Sort list by using the comparator.
Collections.sort(ll, r); for(int i : ll)
System.out.print("List sorted in reverse: System.out.print(i + " ");
"); System.out.println();
for(int i : ll) System.out.println("Minimum: " +
System.out.print(i+ " "); Collections.min(ll));
System.out.println(); System.out.println("Maximum: " +
Collections.max(ll));
// Shuffle list.
}
Collections.shuffle(ll);
}
// Display randomized list.
Collection algorithm - Arrays
• The Arrays class provides various methods that are useful when
working with arrays. These methods help bridge the gap between
collections and arrays.
• The binarySearch( ) method uses a binary search to find a specified
value. This method must be applied to sorted arrays.
/ Demonstrate Arrays
display(array);
import java.util.*;
// Sort and display the arrayArrays.sort(array);
class ArraysDemo {
System.out.print("After sorting again: ");
public static void main(String args[]) { display(array);
// Allocate and initialize array. // Binary search for -9.
int array[] = new int[10]; System.out.print("The value -9 is at location ");
for(int i = 0; i < 10; i++) int index =
array[i] = -3 * i; Arrays.binarySearch(array, -9);
// Display, sort, and display the array. System.out.println(index);
System.out.print("Original contents: "); }
display(array); static void display(int array[]) {

Arrays.sort(array); for(int i: array)


System.out.print(i + " ");
System.out.print("Sorted: ");
System.out.println();
display(array);
}
// Fill and display the array.
}
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
Module 2 : String handling
• The String Constructors, String Length, Special String Operations,
Character Extraction, String Comparison, Searching Strings, Modifying
a String, Data Conversion Using value Of(), Changing the Case of
Characters Within a String, joining strings, Additional String Methods,
StringBuffer , String Builder.
StringBuffer Class
• StringBuffer is a peer class of String that provides much of the
functionality of strings. The string represents fixed-length, immutable
character sequences while StringBuffer represents growable and
writable character sequences.
• StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
• It will automatically grow to make room for such additions and often
has more characters pre allocated than are actually needed, to allow
room for growth.
StringBuffer class Constructors
• StringBuffer(): creates an empty string buffer with an initial capacity
of 16.
• Ex: StringBuffer sb = new StringBuffer();
• StringBuffer(String str): creates a string buffer with the specified
string.
StringBuffer sb = new StringBuffer(“welcome”);
• StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
• StringBuffer sb = new StringBuffer(5);
StringBuffer Class methods
StringBuffer Class Methods
StringBuffer Class Methods
StringBuffer Class Methods
StringBuffer Class Methods
StringBuffer Class Methods
• output
StringBuffer Class Methods
StringBuffer class methods
StringBuffer class methods
StringBuffer class methods
StringBuffer class methods
• Introducing Swing: The Origin of Swing, Swing Is Built on AWT, Two
Key Swing Features, The MVC Connection, Components and
Containers, The Swing Packages, A Simple Swing Application, Event
Handling, Painting in Swing,
• Exploring Swing: JLabel and Image Icon, JTextField, the Swing
Buttons-JButton, JToggleButton, Check, Boxes, Radio Buttons

You might also like