JAVA Module 1
JAVA Module 1
ANS.
• The Java Collections Framework (JCF) is a set of classes and interfaces that
provide a standard way to handle collections in Java.
• It's like a toolkit that Java developers use to work with groups of objects efficiently.
• By using the Java Collections Framework, developers can write code that is more
reusable, flexible, and maintainable.
I. add addAll boolean add(E obj): adds obj to the invoking collection. Returns
true if obj was added to the collection. Returns false if obj is already a
member of the collection and the collection does not allow duplicates.
II. addAll boolean addAll(Collection c): Adds all the elements of c to the
invoking collection. Returns true if the operation succeeded (i.e., the
elements were added). Otherwise, returns false.
III. clear void clear(): Removes all elements from the invoking collection.
IV. contains boolean contains(Object obj): Returns true if obj is an element of
the invoking collection. Otherwise, it returns false.
V. containsAll boolean containsAll(Collection c): Returns true if the invoking
collection contains all elements of c. Otherwise, it returns false.
VI. equals boolean equals(Object obj): Returns true if the invoking collection
and obj are equal. Otherwise, returns false.
VII. hashCode int hashCode(): Returns the hash code for the invoking collection.
VIII. isEmpty boolean isEmpty(): Returns true if the invoking collection is empty.
Otherwise, it returns false.
IX. iterator Iterator iterator(): Returns an iterator for the invoking collection.
X. remove boolean remove(Object obj): Removes one instance of obj from the
invoking collection. Returns true if the element was removed. Otherwise, it
returns false
2. Implement a java program to demonstrate creating an ArrayList, adding
elements, removing elements, sorting elements of ArrayList. Also illustrate
the use of toArray() method.
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> arrayList = new ArrayList<>();
// Adding elements to the ArrayList
arrayList.add(5);
arrayList.add(2);
arrayList.add(7);
arrayList.add(3);
arrayList.add(9);
// Printing the ArrayList
System.out.println("Original ArrayList: " + arrayList);
// Removing an element
arrayList.remove(Integer.valueOf(3));
System.out.println("ArrayList after removing element 3: " + arrayList);
// Sorting the ArrayList
Collections.sort(arrayList);
System.out.println("Sorted ArrayList: " + arrayList)
// Using toArray() method to convert ArrayList to an array
Integer[] array = arrayList.toArray(new Integer[arrayList.size()]);
System.out.println("Array after conversion: ");
for (Integer num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
al.add("B");
al.add("D");
al.add("F");
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
The meaning of capacity and fill ratio is the same as for HashSet, described
earlier. The
default capacity is 16.
The default fill ratio is 0.75.
HashMap implements Map and extends AbstractMap. It does not add any
methods of
its own.
import java.util.*;
TreeMap
The TreeMap class extends AbstractMap and implements the NavigableMap interface.
A TreeMap provides an efficient means of storing key/value pairs in sorted order and
allows
rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its
Here, K specifies the type of keys, and V specifies the type of values.
TreeMap( )
The first form constructs an empty tree map that will be sorted by using the natural
order of
its keys. The second form constructs an empty tree-based map that will be sorted by
using the
Comparator comp. (Comparators are discussed later in this chapter.) The third form
initializes
a tree map with the entries from m, which will be sorted by using the natural order of the
keys. The fourth form initializes a tree map with the entries from sm, which will be
sorted in
TreeMap has no methods beyond those specified by the NavigableMap interface and
import java.util.*;
map.put("C", 3);
map.put("A", 1);
map.put("B", 2);
Legacy classes are the old collection classes that were part of Java 1.0, before the Java
Collections Framework (JCF) was introduced in Java 1.2.
1. Vector
2. Stack
3. Hashtable
4. Enumeration (interface)
Characteristics:
They are not part of the java.util.Collection hierarchy, but were later retrofitted to
implement collection interfaces.
import java.util.Vector;
v.add("A");
v.add("B");
significantly increased its power and streamlined its use. The changes were the addition
of
Generics
because the entire Collections Framework has been reengineered for it. All collections
are
now generic, and many of the methods that operate on collections take generic type
parameters Generics add the one feature that collections had been missing: type
safety.
Prior to generics, all collections stored Object references, which meant that any
collection
could store any type of object. Thus, it was possible to accidentally store in compatible
type s
in a collection.
Doing so could result in run-time type mismatch errors. With generics, it is possible to
explicitly state the type of data being stored, and run-time type mismatch errors can be
avoided.
Here, E specifies the type of element that will be stored.- Operations: add, remove, get,
set- Constructors:
size of 10.
Vector(int size): creates a vector whose initial capacity
is specified by size.
upward.
elements of collection c.
Here, E specifies the type of element stored in the stack.- Operations: push, pop, peek,
empty
storage repository.- Given a key and value, you can store the value in a
Dictionary object.- Oncethevalue is stored, you can retrieve it by using its key.
key/value pairs.
of values.
IV. Hashtable- Hashtable was part of the original java.util and is a concrete
8. Create a class STUDENT with two private members: USN, Nameusing LinkedList
class in Java. Write a program to add at least 3 objects of the above STUDENT class
and display the data.
import java.util.LinkedList;
class STUDENT {
this.USN = USN;
this.Name = Name;
@Override
}
}
LinkedList<>();
studentList.add(new STUDENT("USN003",
"Charlie"));
System.out.println(student);
Methods:- lower(E e): returns the greatest element in the set that is
strictly less than the specified element.- floor(E e): returns the greatest element in the
set that is
less than or equal to the specified element.- ceiling(E e): returns the least element in
the set that is
greater than or equal to the specified element.- higher(E e): returns the least element in
the set that is
strictly greater than the specified element.- pollFirst(): retrieves and removes the first
(lowest) element
of the set.- pollLast(): retrieves and removes the last (highest) element
of the set.
import java.util.NavigableSet;
import java.util.TreeSet;
set.add(1);
set.add(3);
set.add(5);
set.add(7);
set.lower(5));
System.out.println("Ceiling of 5: " +
set.ceiling(5));
set.higher(5));
set.pollFirst());
Ans.
1. Create a User-Defined Class
Define fields, constructors, and optionally override methods like toString(), equals(),
and hashCode().
2. Create a Collection
Use any suitable collection (ArrayList, LinkedList, HashSet, etc.) with generics to
specify the custom class type.
4. Access or Iterate
import java.util.*;
class Address {
name = n;
street = s;
city = c;
state = st;
code = cd;
}}
class MailList {
System.out.println(element + "\n");
System.out.println();
1.collection
2.list
4.sorted set
4.queue
Ans.
• The Java Collections Framework (JCF) is a set of classes and interfaces that
provide a standard way to handle collections in Java.
• It's like a toolkit that Java developers use to work with groups of objects efficiently.
1.collection
querying elements.
contains(Object o): Returns true if the collection contains the specified element.
2.List
List interface extends collection interface. It includes new method. Which are
given below.
Inserts obj into the invoking list at the index passed in index.
Any pre existing elements at or beyond the point of insertion are shifted up.
Inserts all elements of C into the invoking list at the index passed in
index . Any pre existing elements at or beyond the point of insertion are shifted up.
Thus, no elements are overwritten. Returns true if the invoking list changes and
E get(int index )
Returns the object stored at the specified index within the invoking collection.
Returns the index of the last instance of obj in the invoking list. If obj is not an
ListIterator<E> listIterator( )
Returns an iterator to the invoking list that begins at the specified index.
E remove(int index )
Removes the element at position index from the invoking list and returns the deleted
element. The resulting list is compacted. That is, the indexes of subsequent elements
Assigns obj to the location specified by index within the invoking list.
Returns a list that includes elements from start to end –1 in the invoking list.
Elements in the returned list are also referenced by the invoking object.
3.sorted set
The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
SortedSet is a generic interface that has this declaration: interface SortedSet<E> Here,
In addition to those methods defined by Set, the SortedSet interface declares the
methods.
Returns the invoking sorted set’s comparator.If the natural ordering is used for this
set, null is returned. E first( )
Returns a SortedSet containing those elements less than end that are contained in the
Elements in the returned sorted set are also referenced by the invoking sorted set.
E last( )
Returns a SortedSet that includes those elements between start and end– 1. Elements
Returns a SortedSet that contains those elements greater than or equal to start that are
contained in the sorted set. Elements in the returned set are also referenced by the
invoking object.
a set.
4.Queue
The Queue interface extends Collection and declares the behaviour of a queue, which is
often a first-in, first-out list. However, there are types of queues in which the ordering is
based upon other criteria. Queue is a generic interface that has this declaration:
interface Queue<E>
E element( )
Returns the element at the head of the queue. The element is not removed. It
Attempts to add obj to the queue. Returns true if obj was added and false otherwise.
E peek( )
Returns the element at the head of the queue. It returns null if the queue is empty. The
E poll( )
Returns the element at the head of the queue, removing the element in the process. It
E remove( )
Removes the element at the head of the queue, returning the element in the process. It