0% found this document useful (0 votes)
15 views11 pages

AP Unit 3 Updated 24-25

The document provides an overview of Java Collections Framework, detailing various ways to store values in JVM, including variables, class objects, arrays, and collections. It explains the technical definition of collections, their types, and commonly used classes such as ArrayList, LinkedList, HashSet, and TreeSet, along with their functionalities. Additionally, it covers the dynamic nature of ArrayLists, the structure of LinkedLists, and the hashing mechanism of HashSets.

Uploaded by

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

AP Unit 3 Updated 24-25

The document provides an overview of Java Collections Framework, detailing various ways to store values in JVM, including variables, class objects, arrays, and collections. It explains the technical definition of collections, their types, and commonly used classes such as ArrayList, LinkedList, HashSet, and TreeSet, along with their functionalities. Additionally, it covers the dynamic nature of ArrayLists, the structure of LinkedLists, and the hashing mechanism of HashSets.

Uploaded by

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

Unit III

Before Collections:
There are 4 ways to store values in JVM
1. Using variables : can store only one value
2. Using class object : can store multiple fixed number of values of different types
3. Using array object : can store multiple fixed number of values of same type
4. Using collections : can store multiple objects of same and different types
without size limitation

What is Collection?
In general terms a collection is a “group of objects”

Technical Definition:
Collection is a container object. It is used for storing homogeneous and heterogeneous, unique and
duplicate objects without size limitation and further it is used for sending objects at a time from one
class methods to other class methods as method arguments and return type with single name across
multiple layers of the project.
∙ Before java 1.2 it is called simply Java.util package

∙ From java 1.2 onwards its all classes together called as Collections Framework

∙ From java 5 onwards they have added new concepts called Collections and Generics
Java Collections Framework all classes are divided into following 3 different types of classes.

COLLECFTION FRAME WORK OF

Classes
1. Container Objects classes
2. Cursor Objects classes
3. Utility Objects classes
1. Container Objects classes: Following 4 Interfaces are called container objects
1. List <T> 🡪 HashSet <T>, LinkedHashSet<T>

2. Set <T> 🡪 Stack <T>, LinkedList<T>, ArrayList<T>, Vector<T>

3. Map <K,V> 🡪 HashMap <K,V>, Hashtable<K,V>

4. Queue <T> 🡪 LinkedList <T>


<T> Represents generic type parameter, i.e which type of elements are being stored.

2. Cursor objects are retrieving objects


1. Enumeration
2. Iterator
3. ListIterator

3. Utility Objects: it is nothing but a class that is given to perform different operations on container
objects are called utility objects i.e two classes
1. Collections class
2. Arrays

The Collection in Java is a framework that provides architecture to store and manipulate the group of
objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
∙ searching,

∙ sorting,

∙ insertion,

∙ manipulation,

∙ deletion etc.
4. Java collection framework provide many Interfaces and classes

COMMONLY USED COLLECTION CLASSES


Java collection class is used exclusively with static methods that operate on or return collections. It
inherits Object class.
The important points about Java Collections class are:
∙ Java Collection class supports the polymorphic algorithms that operate on collections.

∙ Java Collection class throws a NullPointerException if the collections or class objects provided to
them are null.
List of Collection Classes:
1) Array List
2) Linked List
3) Vector
4) Stack
5) Priority Queue
6) Array Deque
7) Hash Set
8) Tree Set
9) LinkedHashSet
10) SortedSet
Collections: Overview of Java Collection frame work, commonly used Collection classes – Array List,
Linked List, Hash Set, Tree Set, Collection Interfaces – Collection, List, Set. Accessing Collection via
iterator, working with Map. Legacy classes and interfaces – Vector, Hashtable, Stack, Dictionary,
Enumeration interface.

NOTE In addition to the collection classes, several legacy classes, such as Vector, Stack, and
Hashtable, have been reengineered to support collections.

The ArrayList Class


The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic
class that has this declaration: class ArrayList<E>

Here, E specifies the type of objects that the list will hold. ArrayList supports dynamic arrays that can
grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements an array will hold.
But, sometimes, you may not know until run time precisely how large an array you need. To handle this
situation, the Collections Framework defines ArrayList. In essence, an ArrayList is a variable-length
array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array
lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array can be shrunk.

NOTE Dynamic arrays are also supported by the legacy class Vector, which is described later
in this chapter.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is
initialized with the elements of the collection c. The third constructor builds an array list that has the
specified initial capacity. The capacity is the size of the underlying array that is used to store the
elements. The capacity grows automatically as elements are added to an array list.
The following program shows a simple use of ArrayList. An array list is created for objects of type
String, and then several strings are added to it. (Recall that a quoted string is translated into a String
object.) The list is then displayed. Some of the elements are removed and the list is displayed again.

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

Notice that a1 starts out empty and grows as elements are added to it. When elements are
removed, its size is reduced.

In the preceding example, the contents of a collection are displayed using the default conversion
provided by toString( ) , which was inherited from AbstractCollection. Although it is sufficient for
short, sample programs, you seldom use this method to display the contents of a real-world collection.
Usually, you provide your own output routines. But, for the next few examples, the default output
created by toString( ) is sufficient.

Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can
increase the capacity of an ArrayList object manually by calling ensureCapacity( ).

You might want to do this if you know in advance that you will be storing many more items in the
collection than it can currently hold. By increasing its capacity once, at the start, you can prevent
several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary
ones improves performance. The signature for ensureCapacity( ) is shown here:
void ensureCapacity(int cap)

Here, cap is the new capacity.


Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is
precisely as large as the number of items that it is currently holding, call trimToSize( ), shown here:
void trimToSize( )

Obtaining an Array from an ArrayList


When working with ArrayList, you will sometimes want to obtain an actual array that contains the
contents of the list. You can do this by calling toArray( ), which is defined by Collection.

Several reasons exist why you might want to convert a collection into an array, such as:
• To obtain faster processing times for certain operations
• To pass an array to a method that is not overloaded to accept a collection
• To integrate collection-based code with legacy code that does not understand collections
Whatever the reason, converting an ArrayList to an array is a trivial matter.

There are two versions of toArray( ), which are shown again


Object[ ] toArray( )
<T> T[ ] toArray(T array[ ])

The first returns an array of Object. The second returns an array of elements that have the same type
as T. Normally, the second form is more convenient because it returns the proper type of array. The
following program demonstrates its use:

// Convert an ArrayList into an array.


import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
// Create an array list.
ArrayList<Integer> al = new ArrayList<Integer>();
// Add elements to the array list.
al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of al: " + al);
// Get the array.
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
// Sum the array.
for(int i : ia) sum += i;
System.out.println("Sum is: " + sum);
}
}
The output from the program is shown here:
Contents of al: [1, 2, 3, 4]
Sum is: 10

The program begins by creating a collection of integers. Next, toArray( ) is called and it obtains an
array of Integers. Then, the contents of that array are summed by use of a for-each style for loop.

There is something else of interest in this program. As you know, collections can store only references
to, not values of, primitive types. However, autoboxing makes it possible to pass values of type int to
add( ) without having to manually wrap them within an Integer, as the program shows. Autoboxing
causes them to be automatically wrapped. In this way, autoboxing significantly improves the ease with
which collections can be used to store primitive values.

The LinkedList Class


The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this
declaration:
class LinkedList<E>

Here, E specifies the type of objects that the list will hold. LinkedList has the two constructors shown
here:
LinkedList( )
LinkedList(Collection<? extends E> c)

The first constructor builds an empty linked list. The second constructor builds a linked list that is
initialized with the elements of the collection c. Because LinkedList implements the Deque interface,
you have access to the methods defined by Deque. For example, to add elements to the start of a list
you can use addFirst( ) or offerFirst( ). To add elements to the end of the list, use addLast( ) or
offerLast( ). To obtain the first element, you can use getFirst( ) or peekFirst( ). To obtain the last
element, use getLast( ) or peekLast( ). To remove the first element, use removeFirst( ) or pollFirst(
). To remove the last element, use removeLast( ) or pollLast( ).

The following program illustrates LinkedList:


// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// Get and set a value.
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
The output from this program is shown here:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

Because LinkedList implements the List interface, calls to add(E) append items to the end of the list,
as do calls to addLast( ). To insert items at a specific location, use the add(int, E) form of add( ), as
illustrated by the call to add(1, “A2”) in the example. Notice how the third element in ll is changed by
employing calls to get( ) and set( ). To obtain the current value of an element, pass get( ) the index at
which the element is stored. To assign a new value to that index, pass set( ) the index and its new
value.

The HashSet Class


HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a
hash table for storage. HashSet is a generic class that has this declaration:

class HashSet<E>
Here, E specifies the type of objects that the set will hold.
As most readers likely know, a hash table stores information by using a mechanism called hashing. In
hashing, the informational content of a key is used to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored. The
transformation of the key into its hash code is performed automatically— you never see the hash code
itself. Also, your code can’t directly index the hash table. The advantage of hashing is that it allows the
execution time of add( ), contains( ), remove( ), and size( ) to remain constant even for large sets.

The following constructors are defined:


HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)

The first form constructs a default hash set. The second form initializes the hash set by using the
elements of c. The third form initializes the capacity of the hash set to capacity. (The default capacity is
16.) The fourth form initializes both the capacity and the fill ratio (also called load capacity) of the hash
set from its arguments. The fill ratio must be between 0.0 and 1.0, and it determines how full the hash
set can be before it is resized upward. Specifically, when the number of elements is greater than the
capacity of the hash set multiplied by its fill ratio, the hash set is expanded. For constructors that do
not take a fill ratio, 0.75 is used. HashSet does not define any additional methods beyond those
provided by its superclasses and interfaces.
It is important to note that HashSet does not guarantee the order of its elements, because the process
of hashing doesn’t usually lend itself to the creation of sorted sets. If you need sorted storage, then
another collection, such as TreeSet, is a better choice.

Here is an example that demonstrates HashSet:


// Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// Create a hash set.
HashSet<String> hs = new HashSet<String>();
// Add elements to the hash set.
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
The following is the output from this program:
[D, A, F, C, B, E]
As explained, the elements are not stored in sorted order, and the precise output may vary.

The LinkedHashSet Class


The LinkedHashSet class extends HashSet and adds no members of its own. It is a generic class that
has this declaration:
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold. Its constructors parallel those in HashSet.

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were
inserted. This allows insertion-order iteration over the set. That is, when cycling through a
LinkedHashSet using an iterator, the elements will be returned in the order in which they were
inserted. This is also the order in which they are contained in the string returned by toString( ) when
called on a LinkedHashSet object. To see the effect of LinkedHashSet, try
substituting LinkedHashSet for HashSet in the preceding program. The output will be [B, A, D, E,
C, F] which is the order in which the elements were inserted.

The TreeSet Class


TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection that
uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are
quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information
that must be found quickly. TreeSet is a generic class that has this declaration:

class TreeSet<E>
Here, E specifies the type of objects that the set will hold.

TreeSet has the following constructors:


TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)

The first form constructs an empty tree set that will be sorted in ascending order according to the
natural order of its elements. The second form builds a tree set that contains the elements of c. The
third form constructs an empty tree set that will be sorted according to the comparator specified by
comp. (Comparators are described later in this chapter.) The fourth form builds a tree set that contains
the elements of ss.

Here is an example that demonstrates a TreeSet:


// Demonstrate TreeSet.
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet<String> ts = new TreeSet<String>();
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
The output from this program is shown here:
[A, B, C, D, E, F]
As explained, because TreeSet stores its elements in a tree, they are automatically arranged
in sorted order, as the output confirms.

Because TreeSet implements the NavigableSet interface (which was added by Java SE 6), you can use
the methods defined by NavigableSet to retrieve elements of a TreeSet. For example, assuming the
preceding program, the following statement uses subSet( ) to obtain a subset of ts that contains the
elements between C (inclusive) and F (exclusive).
It then displays the resulting set.
System.out.println(ts.subSet()("C", "F"));
The output from this statement is shown here:
[C, D, E]
You might want to experiment with the other methods defined by NavigableSet.

WORKING WITH MAP


A map contains values on the basis of key, i.e. key and value pair. Each key and value pair
is known as an entry. A Map contains unique keys.A Map is useful if you have to search,
update or delete elements on the basis of a key. There are two interfaces for
implementing Map in java: Map and SortedMap, and three classes: HashMap,
LinkedHashMap, and TreeMap.

//Demonstration of Map
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}}}

LEGACY CLASSES AND INTERFACES


It only defined several classes and interfaces that provide methods for storing objects.
When Collections framework were added in J2SE 1.2, the original classes were
reengineered to support the collection interface. These classes are also known as Legacy
classes. All the legacy classes are synchronized. The java.util package defines the
following legacy classes:

List of Legacy Classes:


 HashTable
 Stack
 Dictionary
 Properties
 Vector
There is only one Legacy interface that is Enumeration interface.

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.
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{ Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{ System.out.println(data.nextElement()); } } }

HASHTABLE: The Hashtable class is similar to HashMap. It also contains the data into
key/value pairs. It doesn't allow to enter any null key and value because it is
synchronized. Just like Vector,
Hashtable also has the following four constructors.

import java.util.*;
class HashtableExample
{ public static void main(String args[])
{ Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
student.put(new Integer(103), "Aria");
student.put(new Integer(104), "Ally");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{ Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
} } }

STACK: Stack class extends Vector class, which follows the LIFO(LAST IN FIRST OUT)
principal
for its elements. The stack implementation has only one default constructor, i.e., Stack()
import java.util.*;
class StackExample {
public static void main(String args[]) {
Stack stack = new Stack();
stack.push("Emma");
stack.push("Adele");
stack.push("Aria");
stack.push("Ally");
stack.push("Paul");
Enumeration enum1 = stack.elements();
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
stack.pop();
stack.pop();
stack.pop();
System.out.println("\nAfter removing three elements from stack");
Enumeration enum2 = stack.elements();
while(enum2.hasMoreElements())
System.out.print(enum2.nextElement()+" "); }}

DICTIONARY: The Dictionary class operates much like Map and represents the key/value
storage
repository. The Dictionary class is an abstract class that stores the data into the key/value
pair. We
can define the dictionary as a list of key/value pairs.

import java.util.*;
public class DictionaryExample
{ public static void main(String[] args)
{ // Initializing Dictionary object
Dictionary student = new Hashtable();
// Using put() method to add elements
student.put("101", "Emma");
student.put("102", "Adele");
student.put("103", "Aria");
student.put("104", "Ally");
student.put("105", "Paul");
// Using the remove() method
System.out.println("\nDelete : " + student.remove("103"));
System.out.println("The name of the deleted student : " +
student.get("123"));
System.out.println("\nThe size of the student dictionary is : " +
student.size());
} }

ENUMERATION INTERFACE
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.This legacy interface has been
superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for
new code. However, it is used by several methods defined by the legacy classes such as
Vector and Properties, is used by several other API classes, and is currently in widespread
use in application code.

import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement()); } } }

You might also like