0% found this document useful (0 votes)
3 views18 pages

JAVA Module 1

The document provides a comprehensive overview of the Java Collections Framework, including its definition, methods, and various collection classes such as ArrayList, HashMap, and TreeMap. It also discusses legacy classes, recent changes to the framework, and demonstrates how to use user-defined classes with collections. Additionally, it includes sample code snippets to illustrate the concepts discussed.

Uploaded by

p70188167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

JAVA Module 1

The document provides a comprehensive overview of the Java Collections Framework, including its definition, methods, and various collection classes such as ArrayList, HashMap, and TreeMap. It also discusses legacy classes, recent changes to the framework, and demonstrates how to use user-defined classes with collections. Additionally, it includes sample code snippets to illustrate the concepts discussed.

Uploaded by

p70188167
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

JAVA Module 1

1. What is a Collection Framework? Explain the methods defined by


Collections Framework.

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.

• The Java Collections Framework provides a unified architecture for handling


collections of objects in Java.

• It includes interfaces, implementations, utility classes, and algorithms to make


working with collections easier and more efficient.

• By using the Java Collections Framework, developers can write code that is more
reusable, flexible, and maintainable.

Methods in collection interface:

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();
}
}

3.Accesing a collection via interpreter with example.


ANS.
Accessing a collection Via an Iterator:
Before you can access a collection through an iterator, you must obtain one.
Each of
the collection classes provides an iterator( ) method that returns an iterator to
the start of
the collection.
By using this iterator object, you can access each element in the collection.
Element
at a time. In general, to use an iterator to cycle through the contents of a
collection, follow
these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s
iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( )
returns true.
3. Within the loop, obtain each element by calling next( ).
4. For collections that implement List, you can also obtain an iterator by calling
listIterator( ).
5. As explained, a list iterator gives you the ability to access the collection in
either the
forward or backward direction and lets you modify an element.
6. Otherwise, ListIterator is used just like Iterator.

import java.util.*;
class IteratorDemo {
public static void main(String args[]) {

ArrayList<String> al = new ArrayList<String>();


al.add("C");
al.add("A");
al.add("E");

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+

4.Explain hash map and tree map with example


ANS.
HashMap:
The HashMap class extends AbstractMap and implements the Map interface. It
uses a hash table to store the map.
This allows the execution time of get( ) and put( ) to remain constant
even for large sets. HashMap is a generic class that has this declaration:
class HashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.

The following constructors are defined:


HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
The first form constructs a default hash map. The second form initializes the
hash map by
using the elements of m. The third form initializes the capacity of the hash map
to capacity.
The fourth form initializes both the capacity and fill ratio of the hash map by
using its
arguments.

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.*;

public class SimpleMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
System.out.println(map.get("A")); // Output: 1
}
}

TreeMap

The TreeMap class extends AbstractMap and implements the NavigableMap interface.

It creates maps stored in a tree structure.

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

elements will be sorted in ascending key order.

TreeMap is a generic class that has this declaration:


class TreeMap<K, V>

Here, K specifies the type of keys, and V specifies the type of values.

The following TreeMap constructors are defined:

TreeMap( )

TreeMap(Comparator<? super K> comp)

TreeMap(Map<? extends K, ? extends V> m)

TreeMap(SortedMap<K, ? extends V> sm)

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

the same order as sm.

TreeMap has no methods beyond those specified by the NavigableMap interface and

the AbstractMap class.

import java.util.*;

public class SimpleTreeMap {

public static void main(String[] args) {

TreeMap<String, Integer> map = new TreeMap<>();

map.put("C", 3);

map.put("A", 1);

map.put("B", 2);

System.out.println(map); // Output: {A=1, B=2, C=3}


}

5.Explain legacy class

What are Legacy Classes?

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.

These classes are still supported in Java for backward compatibility.

Main Legacy Classes:

1. Vector

2. Stack

3. Hashtable

4. Enumeration (interface)

5. Dictionary (abstract class)

Characteristics:

Most legacy classes are synchronized (thread-safe).

They are not part of the java.util.Collection hierarchy, but were later retrofitted to
implement collection interfaces.

import java.util.Vector;

public class LegacyExample {

public static void main(String[] args) {

Vector<String> v = new Vector<>();

v.add("A");

v.add("B");

System.out.println(v); // Output: [A, B]


}

6.What are the recent changes to collection framework?

Recently, the Collections Framework underwent a fundamental change that

significantly increased its power and streamlined its use. The changes were the addition
of

generics, autoboxing/unboxing, and the for-each style for loop.

Generics

The addition of generics caused a significant change to the Collections Framework

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.

7. Explain any four legacy classes of Java’s Collection Framework.

I. Vector- Vector implements a dynamic array that grows as needed to accommodate


new elements.- It is similar to ArrayList, but with two di erences: Vector is synchronized,
and it contains many legacy methods that arenot part of the Collections.- It implements
the List interface.

Vector is declared like this: class Vector<E>

Here, E specifies the type of element that will be stored.- Operations: add, remove, get,
set- Constructors:

Vector( ): creates a default vector, which has an initial

size of 10.
Vector(int size): creates a vector whose initial capacity

is specified by size.

Vector(int size, int incr): 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 that a vector is resized

upward.

Vector(Collection c): creates a vector that contains the

elements of collection c.

II. Stack- Stack is a subclass of Vector that implements a standard

LIFO data structure.

- Stack only defines the default constructor, which creates an

empty stack.- Stack includes all the methods defined by Vector

It is declared as: class Stack<E>

Here, E specifies the type of element stored in the stack.- Operations: push, pop, peek,
empty

III. Dictionary- Dictionary is an abstract class that represents a key/value

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.

Thus, like a map, a dictionary can be thought of as a list of

key/value pairs.

It is declared as: class Dictionary <E>

Here, K specifies the type of keys, and V specifies the type

of values.

IV. Hashtable- Hashtable was part of the original java.util and is a concrete

implementation of a Dictionary.- HashMap, Hashtable stores key/value pairs in a hash


table.- However, neither keys nor values can be null.- Whenusing aHashtable, you
specify an object that is used
as a key, and the value that you want linked to that key.- Thekey is then hashed, and the
resulting hash code is used

as the index at which the value is stored within the table.

It is declared like this: class Hashtable<K,V>- Constructors:

Hashtable( ): default constructor

Hashtable(int size): creates a hash table that has an

initial size specified by size.

Hashtable(int size, float fillRatio): creates a hash

table that has an initial size specified by size and a fill

ratio specified by fillRatio. If you do not specify a fill ratio,

then 0.75 is used

Hashtable(Map m): 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

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 {

private String USN;

private String Name;

public STUDENT(String USN, String Name) {

this.USN = USN;

this.Name = Name;

@Override

public String toString() {

return "USN: " + USN + ", Name: " + Name;

}
}

public class StudentLinkedListExample {

public static void main(String[] args) {

LinkedList<STUDENT> studentList = new

LinkedList<>();

studentList.add(new STUDENT("USN001", "Alice"));

studentList.add(new STUDENT("USN002", "Bob"));

studentList.add(new STUDENT("USN003",

"Charlie"));

for (STUDENT student : studentList) {

System.out.println(student);

9. Explain the methods of NavigableSet class with a sample program.-

The NavigableSet interface in Java is part of the Java Collections Framework.

- It extends the SortedSet interface.

- It provides additional methods to navigate and manipulatethe elements in a sorted


set.

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;

public class NavigableSetExample {

public static void main(String[] args) {

NavigableSet<Integer> set = new TreeSet<>();

set.add(1);

set.add(3);

set.add(5);

set.add(7);

System.out.println("Original set: " + set);

System.out.println("Lower than 5: " +

set.lower(5));

System.out.println("Floor of 5: " + set.floor(5));

System.out.println("Ceiling of 5: " +

set.ceiling(5));

System.out.println("Higher than 5: " +

set.higher(5));

System.out.println("Poll first: " +

set.pollFirst());

System.out.println("Set after pollFirst: " + set);

System.out.println("Poll last: " + set.pollLast());

System.out.println("Set after pollLast: " + set);

10.with a program explain how to store user defined classes in collection

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.

3. Add Objects to the Collection

Use .add() or .put() methods to insert instances of the class.

4. Access or Iterate

Use loops, iterators, or streams to access and process stored objects.

import java.util.*;

class Address {

private String name;

private String street;

private String city;

private String state;

private String code;

Address(String n, String s, String c,

String st, String cd) {

name = n;

street = s;

city = c;

state = st;

code = cd;

public String toString() {

return name + "\n" + street + "\n" +

city + " " + state + " " + code;

}}
class MailList {

public static void main(String args[]) {

LinkedList<Address> ml = new LinkedList<Address>();

ml.add(new Address("J.W. West", "11 Oak Ave",

"Urbana", "IL", "61801"));

ml.add(new Address("Ralph Baker", "1142 Maple Lane",

"Mahomet", "IL", "61853"));

ml.add(new Address("Tom Carlton", "867 Elm St",

"Champaign", "IL", "61820"));

for(Address element : ml)

System.out.println(element + "\n");

System.out.println();

11.what is collection frame work ? exaplain the methods defined by interface

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.

• The Java Collections Framework provides a unified architecture for handling


collections of objects in Java.

• It includes interfaces, implementations, utility classes, and algorithms to make


working with collections easier and more efficient.
• By using the Java Collections Framework, developers can write code that is more
reusable, flexible, and maintainable

1.collection

The Collection Interface

Description: The root interface of the collection hierarchy.

Methods: Defines basic operations common to all collections, such as adding,


removing, and

querying elements.

add(E e): Adds the specified element to the collection.

remove(Object o): Removes the specified element from the collection.

contains(Object o): Returns true if the collection contains the specified element.

size(): Returns the number of elements in the collection.

isEmpty(): Returns true if the collection contains no elements.

iterator(): Returns an iterator over the elements in the collection.

Subinterfaces: List, Set, Queue, Deque

2.List

List interface extends collection interface. It includes new method. Which are

given below.

void add(int index , E obj )

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.

boolean addAll(int index , Collection<? extends E> c )

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

returns false otherwise.

E get(int index )

Returns the object stored at the specified index within the invoking collection.

int indexOf(Object obj )


Returns the index of the first instance of obj in the invoking list. If obj is not an

element of the list, –1 is returned.

int lastIndexOf(Object obj )

Returns the index of the last instance of obj in the invoking list. If obj is not an

element of the list, –1 is returned.

ListIterator<E> listIterator( )

Returns an iterator to the start of the invoking list.

ListIterator<E> listIterator(int index )

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

are decremented by one.

E set(int index , E obj )

Assigns obj to the location specified by index within the invoking list.

List<E> subList(int start , int end )

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

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,

E specifies the type of objects that the set will hold.

In addition to those methods defined by Set, the SortedSet interface declares the

methods.

Comparator<? super E> comparator( )

Returns the invoking sorted set’s comparator.If the natural ordering is used for this
set, null is returned. E first( )

Returns the first element in the invoking sorted set.

SortedSet<E> headSet(E end )

Returns a SortedSet containing those elements less than end that are contained in the

invoking sorted set.

Elements in the returned sorted set are also referenced by the invoking sorted set.

E last( )

Returns the last element in the invoking sorted set.

SortedSet<E> subSet(E start , E end )

Returns a SortedSet that includes those elements between start and end– 1. Elements

in SortedSet<E> tailSet(E start )

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.

Several methods throw a NoSuchElementException when no items are contained in

the invoking set.

A ClassCastException is thrown when an object is in compatible with the elements in

a set.

A NullPointerException is thrown if an attempt is made to use a null object and null

is not allowed in the set.

An IllegalArgumentException is thrown if an invalid argument is used. the returned


collection are also referenced by the invoking object.

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

throws NoSuchElementException if the queue is empty.

boolean offer(E obj )

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

element is not removed.

E poll( )

Returns the element at the head of the queue, removing the element in the process. It

returns null if the queue is empty.

E remove( )

Removes the element at the head of the queue, returning the element in the process. It

throws NoSuchElementException if the queue is empty.

You might also like