Collections and Framework
Collections and Framework
• I have multiple students in a class like stud1,stud2..stud3 all together we can call it a collection
of students.
• In java to represent group of objects into a single entity we need certain number of classes and
interfaces.
• Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.
• Collection framework means it defines the different interfaces and classes by which
we can represent group of objects into a collection.
• I have a three students so collectively I will call as one collection .to represent group of
elements into single entity we need a special classes or interfaces .
Arraylist is equal to new arraylist when I create a object like this I can store group of
elements into a arraylist.
What is interface?
• A method declared using the abstract keyword within an abstract class and does
not have a definition (implementation) is called an abstract method.
• A class is declared abstract using the abstract keyword. It can have zero or more
abstract and non-abstract methods.
// Regular class extends abstract class
class AbstractMethodEx1 extends Multiply {
// abstract class // if the abstract methods are not implemented, compiler will
abstract class Multiply { give an error
public int MultiplyTwo (int num1, int num2) {
// abstract methods return num1 * num2;
// sub class must implement these methods }
public abstract int MultiplyTwo (int n1, int n2); public int MultiplyThree (int num1, int num2, int num3) {
public abstract int MultiplyThree (int n1, int n2, int n3); return num1 * num2 * num3;
}
// regular method with body
public void show() { // main method
System.out.println ("Method of abstract class Multiply"); public static void main (String args[]) {
} Multiply obj = new AbstractMethodEx1();
} System.out.println ("Multiplication of 2 numbers: " +
obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " +
obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
In this example, the Drawable interface has only one method.
Its implementation is provided by Rectangle and Circle classes.
//Interface declaration: by first user In a real scenario, an interface is defined by someone else, but
interface Drawable{ its implementation is provided by different implementation
void draw(); providers. Moreover, it is used by someone else. The
} implementation part is hidden by the user who uses the
//Implementation: by second user interface.
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided
by method e.g. getDrawable()
d.draw();
}}
The relationship between classes and interfaces
What is framework
• It is optional.
Drawbacks of array
• Data structure is not used while implementing array-it cannot support readymade
• ArrayList
• List
• Hashmap
• Hashtable
• Stack
Arrays vs collections
• In array size is fixed.
• If you want add more items it will throw an exception that is index out of
range exception.
• If you want to store less element then rest of the space will be wasted.
• Collections are growable in nature .at runtime we can add or delete items.
• Collections can hold homogenous plus heterogenous data.
• Collections are implemented by underlying data structure. Ready methods
are available. When I create arraylist there is no need to write code.
Collection framework
Interfaces
• Collection(I)-which is a root interface for all other collection related classes and
interfaces which contains common methods which we can use for other collection
objects .
• For example in an organization we have objects like emp1,emp2,emp3.i will
represent as a single entity which is a collection.
• To represent this collection we need certain interfaces and classes .
• In collection we can perform adding a object, removing object and checking existence
of an object.to do this we need some collection methods. Those methods are common
across all collections. Those methods are present inside collection(I).
• Collection(I) is used to representing group of objects as a single entity and which
contains a common methods which are required for other collections .
COLLECTIONS
• Whatever the methods that are available in collection interface the same methods are available in
the list interface
• Suppose I want to store group of elements When I insert a new elements Insertion order should
be preserved.
class Main {
2.toArray(T[] a): This returns an array containing all the elements of the
collection in the same type as the provided array.
import java.util.ArrayList;
Union - to get the union of two sets x and y, we can use x.addAll(y)
Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]
Creating a HashSet
• In order to create a hash set, we must import the java.util.HashSet package first.
• Once we import the package, here is how we can create hash sets in Java.
• capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
• loadFactor - The load factor of this hash set is 0.6. This means, whenever our hash set is
filled by 60%, the elements are moved to a new hash table of double the size of the original
hash table.
Default capacity and load factor
• // HashSet with default capacity and load factor
• HashSet<Integer> numbers1 = new HashSet<>();
• By default,
• addAll() - inserts all the elements of the specified collection to the set
• The Queue interface of the Java collections framework provides the functionality
of the queue data structure. It extends the Collection interface.
When to use?
• We can use whenever objects needs to have prior to processing.
• 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 the queue
is empty.
Map(I)
• get(Object key): Returns the value to which the specified key is mapped, or null if this map
contains no mapping for the key.
• containsKey(Object key): Returns true if this map contains a mapping for the specified key.
• remove(Object key): Removes the mapping for a key from this map if it is present.
List implementations
• Arraylist
• Linked list
• Vector
ArrayList
• addAll()
• removeAll()
• collections.sort(al)
• Collections.shuffle(al)
import java.util.*;
public class ArrayListExample1{
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");
//Printing the arraylist object
System.out.println(list);
}
}
Output:
• Using a Loop-You can also manually add each element of the array to
an ArrayList using a loop
import java.util.ArrayList;
import java.util.Collections;
[1, 2, 3]
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
class Main {
public static void main(String[] args){
LinkedList: [Dog, Cat, Cow]
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
collections.
Methods of Iterator
• In Java, comparators are objects used to compare objects for sorting or ordering
purposes
Methods of comparator
• compare(T o1, T o2): This is the core method of the Comparator interface. It
compares two objects of type T and returns an integer value representing their
relative ordering.
• In Java, the compare() method is part of the Comparator interface. This method is
used to compare two objects of a particular type to determine their order.
• The compare() method returns an integer value indicating the relationship
between the two objects being compared.
int compare(T obj1, T obj2);
Where:
T is the type of objects being compared.
obj1 and obj2 are the two objects being compared
compare() method
• in Java, the java.util.Collection interface provides the foundation for various collection
classes, each offering different algorithms for manipulating and accessing their
elements.
• Here are some key collection algorithms available in Java:
1.Sorting Algorithms: The Collections class provides several static methods for sorting
collections. The most commonly used method is Collections.sort(List<T> list), which
sorts the elements of the specified list into ascending order.
2. Searching Algorithms: The Collections class also provides methods for searching
elements within collections, such as binarySearch(List<? extends Comparable<?
super T>> list, T key). This method searches for the specified element using the binary
search algorithm.
The Collection Algorithms
• Shuffling Algorithms: The Collections class offers shuffle(List<?> list) method,
which randomly permutes the elements in a list.
• Copying Algorithms: The Collections class provides methods like copy(List<? super
T> dest, List<? extends T> src) to copy elements from one list to another.
• Reversing Algorithms: Collections.reverse(List<?> list) reverses the order of the
elements in a list.Filling Algorithms:
• Collections.fill(List<? super T> list, T obj) method replaces all of the elements of the
specified list with the specified element.
• Frequency Counting Algorithms: Collections.frequency(Collection<?> c, Object o)
returns the number of elements in the specified collection equal to the specified object.
import java.util.*;
Output
Sorted numbers in ascending order: [1, 2, 5, 7, 9]
Sorted numbers in descending order: [9, 7, 5, 2, 1]
import java.util.*;
Output
Sorted numbers in ascending order: [1, 2, 5, 7, 9]
Sorted numbers in descending order: [1, 2, 5, 7, 9]
Custom sort
import java.util.*;
System.out.println("Original list:");
System.out.println(list);
System.out.println("Shuffled list:");
System.out.println(list);
}
}
Searching algorithms
Linear Search: It sequentially checks each element of the list until a match is found
or the whole list has been searched.
Binary Search: It works on sorted arrays by repeatedly dividing the search interval
in half until the value is found or the interval is empty.
Depth-First Search (DFS): It traverses a graph or tree by exploring as far as
possible along each branch before backtracking.
Breadth-First Search (BFS): It explores all neighbor nodes at the present depth
prior to moving on to the nodes at the next depth level.
A Search Algorithm*: It is a best-first search algorithm that uses a heuristic to
efficiently search for a path with the lowest cost.
collections.fill()
import java.util.*;
public class Main {
public static void main(String[] args) {
// Create an array of strings
String[] array = {"apple", "banana", "cherry"};
import java.util.*;
public class FrequencyExample {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
• The min() and max() methods of the Java collections framework are
used to find the minimum and the maximum elements, respectively.
import java.util.Collections;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Output
// Using min()
int min = Collections.min(numbers); Minimum Element: 1
System.out.println("Minimum Element: " + min); Maximum Element: 3
// Using max()
int max = Collections.max(numbers);
System.out.println("Maximum Element: " + max);
}
}
Legacy classes and interfaces
• In Java, "legacy" classes and interfaces typically refer to those that
were part of earlier versions of the Java language and its standard
libraries.
• These classes and interfaces may still be in use but are considered
outdated or superseded by newer alternatives introduced in later
versions of Java.
Enumeration interface
Object nextElement() //It returns the next object in the enumeration i.e. each call to
nextElement() method obtains the next object in the enumeration. It throws
NoSuchElementException when the enumeration is complete.
vector
• 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 class has following four constructors
vector
• Vector() //This creates a default vector, which has an initial size of 10.
• Vector(int size) //This creates a vector whose initial capacity is specified by size.
• Vector(int size, int incr) //This creates a vector whose initial capacity is specified
by size and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time when a vector is resized for addition of
objects.
}
Hashtable class
Hashtable(int size) //This creates a hash table that has an initial size specified by size.
Hashtable(int size, float fillratio) //This creates a hash table that has an initial size specified by size
and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how
full the hash table can be before it is resized upward. Specifically, when the number of elements is
greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded.
Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is initialized with
the elements in m. The capacity of the hash table is set to twice the number of elements in m.
Enumeration e2 = st.elements();
while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
}}