Unit 4 java
Unit 4 java
➔ A collection in Java is a framework that provides an architecture to store ➔ T he Iterator interface provides a way to access elements of a collection
and manipulate a group of objects. sequentially without exposing the underlying structure.
➔ Java Collections can achieve all the operations that you perform on data ➔ It is part of thejava.util packageand is a universaliterator for all
such assearching,sorting,insertion,manipulation,anddeletion. collections.
➔ Key Points: ➔ Key Points:
➔ Collections are used tostore,retrieve,manipulate,and ➔ Methods:
communicate aggregate data. ◆ boolean hasNext(): Returns true if there are more
➔ Collections can hold both homogeneous and heterogeneous data. elements to iterate over.
➔ They can dynamically grow and shrink in size. ◆ E next(): Returns the next element in the iteration.
◆ void remove():Removes the last element returned by
Collection Framework in Java the iterator (optional operation).
➔ T he Collection Framework provides a unified architecture for ➔ Usage:
representing and manipulating collections. ◆ The Iterator interface is used to traverse collections such
➔ All the collections frameworks contain the following: asList,Set, andMap.
➔ Interfaces: These are abstract data types that represent ◆ It supports bothreadandremoveoperations.
collections. The interfaces allow collections to be manipulated
L ist<S tring>list=newArrayList<>();
independently of the details of their representation. list.add("A");
1.Collection 3.Set 5.Map list.add("B" );
2.List 4.Queue list.add("C");
➔ Implementations: These are the concrete implementationsof the
collection interfaces. Essentially, they are reusable data structures. Iterator<S tring>iterator=list.iterator();
1.ArrayList 3. LinkedList 5.HashSet while(iterator.hasNext()){
2.TreeSet 4.HashMap 6.TreeMap Stringelement=iterator.n ext();
System.o
ut.p
rintln(e lement);
➔ Algorithms: These are the methods that perform useful
}
computations, such assearchingandsorting, on objectsthat
implement collection interfaces.
Collection Interface
Advantages of Collection Framework ➔
The Collection interface is the root of the collection hierarchy.
➔ C onsistent API:The collection interfaces have a basicset of operations ➔ It represents a group of objects known as elements.
(such asaddingandremoving) that are extended byall ➔ The Collection interface is part of thejava.utilpackage.
implementations. ➔ Key Points:
➔ Reduces Programming Effort:By providing useful datastructures and ➔ Methods:
algorithms, the Collections Framework reduces the programming effort. ◆ boolean add(E e):Ensures that this collection contains
the specified element.
Java Collections Framework Hierarchy ◆ boolean remove(Object o): Removes a single instance
➔ T he Java Collections Framework is structured as a unified architecture of the specified element from this collection.
for representing and manipulating collections. ◆ int size(): Returns the number of elements in this
➔ The hierarchy is broadly divided into three majorgroups: collection.
➔ List, Set,andQueue, which extend theCollectioninterface, ◆ boolean isEmpty():Returns true if this collection
➔ Map, which is a separate hierarchy. contains no elements.
➔ Here are the important points for each component: ◆ boolean contains(Object o):Returns true if this
➔ Collection Interface collection contains the specified element.
◆ The root interface of the collections framework. ◆ Iterator<E> iterator():Returns an iterator over the
◆ It provides common methods likeadd(),remove(), elements in this collection.
size(),clear(), contains(), anditerator() ◆ boolean addAll(Collection<? extends E> c):Adds allof
➔ Map Interface the elements in the specified collection to this
◆ Represents a mapping between akeyand avalue. collection.
◆ Does not extend the Collection interface. ◆ void clear(): Removes all of the elements from this
◆ Provides methods toput,get,removeelements based collection.
on a key. ➔ Subinterfaces:
1.List 2.Set 3.Queue
CollectionInterface MapInterface ➔ Usage:
| |
+---List Interface +---HashMap ◆ The Collection interface provides the base functionality
| +---ArrayList +---LinkedHashMap for all collections.
| +---LinkedList +---TreeMap
| +---Vector +---Hashtable
| | +---Stack
ollection<S tring>collection=newArrayList<>();
C
| collection.add("A");
+---Set Interface collection.add("B");
| +---HashSet
collection.add("C");
| +---LinkedHashSet
| +---TreeSet
| for(S tringelement:collection){
+---Queue Interface System.o
ut.p
rintln(e lement);
+---PriorityQueue
+---DequeInterface
}
+---ArrayDeque
+---LinkedList Deque
List Interface ➔ B
asic Operations
➔ T he List interface extends the Collection interface and represents an 1.boolean add( e) .void add(int index, element)
6
ordered collection (also known as a sequence). 2. get(int index) 7. set(int index, element)
➔ The user can access elements by their integer index (position in the list) 3. remove(int index) 8.boolean remove(e)
and search for elements in the list. 4. int size() 9. void clear()
➔ Key Points: 5. boolean contains(e)
➔ Methods:
◆ void add(int index, E element):Inserts the specified
importjava.u
til.*;
element at the specified position in this list.
◆ E get(int index):Returns the element at the specified publicclassArrayListExample{
position in this list. publicstaticvoidmain(String[]args){
◆ E set(int index, E element): Replaces the elementat the // Creating an ArrayList
specified position in this list with the specified element. List<String>arrayList=newArrayList<>();
◆ E remove(int index):Removes the element at the
/ / Adding elements
specified position in this list.
arrayList.add("A");
◆ int indexOf(Object o):Returns the index of the first arrayList.add("B");
occurrence of the specified element in this list. arrayList.add("C");
◆ ListIterator<E> listIterator(): Returns a list iteratorover arrayList.add("D");
the elements in this list.
➔ Implementations: / / Accessing elements
1.ArrayList 2. LinkedList 3. Vector 4.Stack System.out.println("Element at index 2:"+arrayList.get(2 ) );
// Iterating elements
➔ Usage: for(S tringelement:arrayList){
◆ T he List interface allows for ordered collections that can System.o ut.p rintln(e lement);
contain duplicate elements. }
// Modifying elements
List<S tring>list=newArrayList<>();
arrayList.set(1 ,"E");
// List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3); method 1
System.out.println("After modification:"+arrayList);
// method 2
// Removing elements
list.add("A");
arrayList.remove("C");
list.add("B");
System.out.println("After removal:"+arrayList);
list.add("C");
// Checking size
System.out.println("Size of ArrayList:"+arrayList.size());
for(inti=0; i<list.size();i++){
// Checking if ArrayList contains an element
System.out.println(list.get(i) );
System.out.println("Does ArrayList contain'A'?"+
}
arrayList.c ontains("A"));
LinkedList
➔
L inkedList is a doubly linked list implementation of the List interface.
➔ It is part of the Java Collections Framework and is found in thejava.util
package.
➔ Unlike ArrayList, which uses a dynamic array, LinkedList uses a doubly
linked list to store elements.
➔ Key Points:
➔ Doubly Linked: Each element in a LinkedList is storedin a node that
contains a reference to the next and previous elements.
➔ Dynamic Size:Can grow and shrink dynamically.
ArrayList ➔ Allows duplicate elements.
➔ Efficient for adding or removing elements anywhere in the list.
➔
A rrayList is a resizable array implementation of the List interface.
➔ Slower than ArrayList for random access (get()), as it requires traversing
➔ It is part of the Java Collections Framework and is found in thejava.util
from the head or tail.
package.
➔ Basic Operations:(Same as ArrayList )
➔ ArrayList allows for dynamic arrays that can grow as needed,
➔ which means it can change its size during runtime. importjava.util.*;
➔ Key Points:
➔ Unlike arrays in Java, ArrayList can grow and shrink in size publicclassLinkedListExample{
dynamically. publicstaticvoidmain(S tring[]args){
// Create a LinkedList
➔ Allows duplicate elements.
LinkedList<S tring>linkedList=newLinkedList<>();
➔ Provides fast random access to elements.
➔ Initial capacity is 10, but it grows automatically as elements are
added.
➔
// Adding elements importjava.u
til.Vector;
linkedList.add("Apple");
linkedList.add("Banana"); publicclassVectorExample{
linkedList.add("Cherry"); publicstaticvoidmain(String[]args){
linkedList.set(1
,"O
range"); // Modifyelement Vector<String>vector=newVector<>();
linkedList.add(2 ,"G
rape"); // Add an element
linkedList.remove("Apple"); // Remove element v ector.a dd("A"); // Adding elements
vector.a dd("B");
/ / Check if "Banana" is present vector.a dd("C" );
booleancontainsBanana=linkedList.contains("Banana");
System.out.println("Does LinkedList contain'Banana'?"+ / / Accessing elements
containsBanana); System.out.println("Element at index 1:"+vector.get(1 ));
// Removing element
S ystem.out.println("Printforward order element"); vector.r emove(2) ;
ListIterator<S tring>iterator=linkedList.listIterator(); // Size of vector
while(iterator.hasNext()){ System.out.println("Size of vector:"+vector.size());
System.out.println(iterator.n
ext()); }
} }
publicclassHashtableExample{ L ist<String>names=newArrayList<>();
publicstaticvoidmain(S tring[]args){ names.a dd("Alice");
// Using Hashtable names.a dd("Bob");
Hashtable<S tring,Integer>hashtable=newHashtable<>(); Collections.s ort(n
ames,Comparator.reverseOrder());// Sorts in
hashtable.put("One",1) ; reverse order
hashtable.put("Two",2) ;
// hashtable.put(null, 3); // Throws NullPointerException Comparable Interface
System.out.println("Hashtable:"+hashtable);
➔
C omparable is an interface in the java.lang package.
} ➔ It declares one method compareTo() which compares the current object
} (this) with another object of the same type.
➔ Classes that implement Comparable can be sorted automatically using
Iterators used in Map and Set methods likeArrays.sort()orCollections.sort().
importjava.util.*;