0% found this document useful (0 votes)
29 views9 pages

Collection Classes

COLLECTION CLASSES IN JAVA

Uploaded by

Preethi Kishore
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)
29 views9 pages

Collection Classes

COLLECTION CLASSES IN JAVA

Uploaded by

Preethi Kishore
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/ 9

24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

UNIT V – COLLECTIONS FRAMEWORK


Collection overview – Recent changes to collection - Collection interface – Collection
classes – Working with maps –Collection algorithms - The legacy classes and interfaces.
Applet class: Types – Basics – Architecture – Skeleton – Display methods – repainting –
Status window – HTML applet tag – Passing parameter - Creating a swing applet -
Painting in swing - A paint example, Exploring swing

Collection classes
Some of the classes provide full implementations that can be used as-is. Others are
abstract, providing skeletal implementations that are used as starting points for creating
concrete collections. None of the collection classes are synchronized.

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,

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

the collection is automatically enlarged. When objects are removed, the array can be
shrunk.
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.
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " + al.size());
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());
System.out.println("Contents of al: " + al);
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

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]
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. 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( ). To remove
the last element, use removeLast( ) or pollLast( ).
The following program illustrates LinkedList:
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> ll = new LinkedList<String>();
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "+ ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "+ ll);
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]
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)

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

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:
import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
HashSet<String> hs = new HashSet<String>();
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]
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

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

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:
import java.util.*;
class TreeSetDemo
{
public static void main(String args[])
{
TreeSet<String> ts = new TreeSet<String>();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

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.
The PriorityQueue Class
PriorityQueue extends AbstractQueue and implements the Queue interface. It
creates a queue that is prioritized based on the queue’s comparator. PriorityQueue is a
generic class that has this declaration:
class PriorityQueue<E>
Here, E specifies the type of objects stored in the queue. PriorityQueues are dynamic,
growing as necessary.
PriorityQueue defines the six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(int capacity, Comparator<? super E> comp)
PriorityQueue(Collection<? extends E> c)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)
The first constructor builds an empty queue. Its starting capacity is 11. The second
constructor builds a queue that has the specified initial capacity. The third constructor
builds a queue with the specified capacity and comparator. The last three constructors
create queues that are initialized with the elements of the collection passed in c. In all
cases, the capacity grows automatically as elements are added.
If no comparator is specified when a PriorityQueue is constructed, then the default
comparator for the type of data stored in the queue is used. The default comparator will
order the queue in ascending order. Thus, the head of the queue will be the smallest
value. However, by providing a custom comparator, you can specify a different ordering
scheme. For example, when storing items that include a time stamp, you could prioritize
the queue such that the oldest items are first in the queue. You can obtain a reference to
the comparator used by a PriorityQueue by calling its comparator( ) method, shown here:
Comparator<? super E> comparator( )
It returns the comparator. If natural ordering is used for the invoking queue, null is
returned. One word of caution: although you can iterate through a PriorityQueue using an

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

iterator, the order of that iteration is undefined. To properly use a PriorityQueue, you
must call methods such as offer( ) and poll( ), which are defined by the Queue interface.
The ArrayDeque Class
Java SE 6 added the ArrayDeque class, which extends AbstractCollection and
implements the Deque interface. It adds no methods of its own. ArrayDeque creates a
dynamic array and has no capacity restrictions. (The Deque interface supports
implementations that restrict capacity, but does not require such restrictions.)
ArrayDeque is a generic class that has this declaration:
class ArrayDeque<E>
Here, E specifies the type of objects stored in the collection.
ArrayDeque defines the following constructors:
ArrayDeque( )
ArrayDeque(int size)
ArrayDeque(Collection<? extends E> c)
The first constructor builds an empty deque. Its starting capacity is 16. The second
constructor builds a deque that has the specified initial capacity. The third constructor
creates a deque that is initialized with the elements of the collection passed in c. In all
cases, the capacity grows as needed to handle the elements added to the deque.
The following program demonstrates ArrayDeque by using it to create a stack:
import java.util.*;
class ArrayDequeDemo
{
public static void main(String args[])
{
ArrayDeque<String> adq = new ArrayDeque<String>();
adq.push("A");
adq.push("B");
adq.push("D");
adq.push("E");
adq.push("F");
System.out.print("Popping the stack: ");
while(adq.peek() != null)
System.out.print(adq.pop() + " ");
System.out.println();
}
}
The output is shown here:

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY


24CA201 - OBJECT ORIENTED PROGRAMMING USING JAVA

Popping the stack: F E D B A


The EnumSet Class
EnumSet extends AbstractSet and implements Set. It is specifically for use with keys of
an enum type. It is a generic class that has this declaration:
class EnumSet<E extends Enum<E>>
Here, E specifies the elements. Notice that E must extend Enum<E>, which enforces the
requirement that the elements must be of the specified enum type. EnumSet defines no
constructors. Instead, it uses the factory methods to create objects. All methods can throw
NullPointerException. The copyOf( ) and range( ) methods can also throw
IllegalArgumentException. Notice that the of( ) method is overloaded a number of times.
This is in the interest of efficiency. Passing a known number of arguments can be faster
than using a var arg parameter when the number of arguments is small.

MCA ROHINI COLLEGE OF ENGINEERING AND TECHNOLOGY

You might also like