Unit 4 Oops With Java
Unit 4 Oops With 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 the[Link] 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.a dd("A" );
[Link] [Link] [Link] list.a dd("B" );
[Link] [Link] list.a dd("C" );
➔ Implementations: These are the concrete implementationsof the
collection interfaces. Essentially, they are reusable data structures. Iterator<S tring>iterator=list.iterator();
[Link] 3. LinkedList [Link] while(iterator.h asNext()){
[Link] [Link] [Link] Stringelement=iterator.n ext();
System.out.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 the[Link]package.
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:
[Link] [Link] [Link]
CollectionInterface MapInterface ➔ Usage:
| |
+---List Interface +---HashMap ◆ The Collection interface provides the base functionality
| +---ArrayList +---LinkedHashMap for all collections.
| +---LinkedList +---TreeMap
| +---Vector +---Hashtable
| | +---Stack
ollection<String>collection=newArrayList<>();
C
| collection.add("A" );
+---Set Interface collection.add("B" );
| +---HashSet
collection.add("C" );
| +---LinkedHashSet
| +---TreeSet
| for(Stringelement:collection){
+---Queue Interface System.out.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 [Link] 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) [Link] 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.util.* ;
element at the specified position in this list.
◆ E get(int index):Returns the element at the specified publicclassArrayListExample{
position in this list. publicstaticvoidmain(S tring[]args){
◆ E set(int index, E element): Replaces the elementat the // Creating an ArrayList
specified position in this list with the specified element. List<S tring>arrayList=newArrayList<>();
◆ E remove(int index):Removes the element at the
/ / Adding elements
specified position in this list.
arrayList.a dd("A" );
◆ int indexOf(Object o):Returns the index of the first arrayList.a dd("B" );
occurrence of the specified element in this list. arrayList.a dd("C" );
◆ ListIterator<E> listIterator(): Returns a list iteratorover arrayList.a dd("D");
the elements in this list.
➔ Implementations: / / Accessing elements
[Link] 2. LinkedList 3. Vector [Link] System.o ut.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(element);
contain duplicate elements. }
// Modifying elements
List<String>list=newArrayList<>();
arrayList.s et(1,"E" );
// List<Integer> numbers = [Link](5, 2, 8, 1, 3); method 1
System.o ut.println("After modification:"+arrayList);
// method 2
// Removing elements
list.add("A" );
arrayList.r emove("C");
list.add("B" );
System.o ut.println("After removal:"+arrayList);
list.add("C" );
// Checking size
System.o ut.println("Size of ArrayList:"+arrayList.s ize());
for(inti=0;i<list.s ize();i++){
// Checking if ArrayList contains an element
System.out.println(list.get(i));
System.o ut.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 the[Link]
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 the[Link]
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.u
til.*;
➔ Key Points:
➔ Unlike arrays in Java, ArrayList can grow and shrink in size publicclassLinkedListExample{
dynamically. publicstaticvoidmain(String[]args){
// Create a LinkedList
➔ Allows duplicate elements.
LinkedList<String>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(S tring[]args){
linkedList.set(1
,"O
range"); // Modifyelement Vector<String>vector=newVector<>();
linkedList.add(2,"Grape"); // Add an element
linkedList.remove("Apple"); // Remove element v ector.add("A" ); // Adding elements
vector.add("B" );
/ / Check if "Banana" is present vector.add("C" );
booleancontainsBanana=linkedList.c ontains("Banana");
System.out.println("Does LinkedList contain'Banana'?"+ / / Accessing elements
containsBanana); System.o ut.println("Element at index 1:"+vector.g et(1
));
// Removing element
S ystem.out.println("Printforward order element"); vector.remove(2 ) ;
ListIterator<String>iterator=linkedList.listIterator(); // Size of vector
while(iterator.h asNext()){ System.o
ut.println("Size of vector:"+vector.size());
System.out.println(iterator.n
ext()); }
} }
publicclassHashtableExample{ L ist<String>names=newArrayList<>();
publicstaticvoidmain(String[]args){ names.a dd("Alice");
// Using Hashtable names.a dd("Bob");
Hashtable<String,Integer>hashtable=newHashtable<>(); Collections.s ort(names,Comparator.reverseOrder());// Sorts in
hashtable.put("One",1) ; reverse order
hashtable.put("Two",2) ;
// [Link](null, 3); // Throws NullPointerException Comparable Interface
System.out.println("Hashtable:"+hashtable);
➔
C omparable is an interface in the [Link] 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 like[Link]()or[Link]().
importjava.util.*;