W11. Collections
W11. Collections
Collections
1
Objectives
• To understand Collections and their benefits
• To understand basic types of collections including
Ordered Lists
Dictionaries
Sets
• To understand and use predefined collections
• To understand and create user defined collections
2
What are Collections?
Collections
• Special type of object is used to organize other objects called a collection.
• It is simply a group of objects bundled together as a single unit.
• Manage and operate on objects as a group.
• Can also refer objects individually when necessary.
• Different operation including searching and sorting can be performed by
collections on group of objects.
Example
• A professor may wish to step through all Student objects registered for a
particular course
3
Collections
• Collections are defined as classes in Java Language.
• Many predefined collection classes are available.
• The package java.util contains a number of utility classes, including
collections
• The collection’s reference variable must be initialized before using.
CollectionType x;
x = new CollectionType();
4
Collections
5
Collections Are Encapsulated
• Only need to know a collection’s public features.
• Virtually all collections provide methods for
• Adding objects
• Removing objects
• Retrieving specific individual objects
• Iterating through the objects in some predetermined order
• Getting a count of the number of objects presently referenced by the collection
• Answering a true/false question as to whether a particular object’s reference is in the
collection or not
6
Generic Types of Collection
1. Ordered lists
2. Dictionaries
3. Sets
7
Types of Collection
• Java Collection framework provides many
• interfaces (Set, List, Queue, Deque, HashMap etc.) and
• classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet etc).
• Java impelments collections using two base interfaces called
collection and map
1. Ordered lists
• ArrayList
2. Dictionaries
• HashMap
• TreeMap
3. Sets
• HashSet
And others…
8
9
Ordered Lists
• An ordered list is a type of collection that allows us to insert items in a
particular order and later retrieve them in that same order.
• Specific objects can also be retrieved based on their position in the list.
• It needn’t be assigned an explicit capacity
• This type of collection automatically expand and shrinks as items are added
or removed.
• By default, items are added at the end of an ordered list, unless explicit
instructions are given to insert an item at a different position.
10
Dictionaries
• A dictionary provides a means for storing each object reference along with a
unique lookup key that can be used to quickly retrieve the object
• also known as a map
• The key is often contrived based on one or more of the object’s attribute
values.
• For example, a Student object’s student ID number would make an excellent
key, because its value is inherently unique for each Student.
• Several references to the same object can be added to given ordered list or
dictionary
11
Dictionaries
12
Sets
• A set is an unordered collection,
• There is no way to ask for a particular item by number/position once it has
been inserted into the set.
• It can be determined whether or not a specific object has been previously
added to the set or not.
• Duplicate entries aren’t allowed in a set.
13
Array – a simple collection
• The official Java syntax for declaring that a variable x will serve as a
reference to an array containing items of a particular data type is as
follows:
datatype[] x;
• An array can contain references to objects.
• Array elements can be accessed using index of the element
double[] data = new double[3];
data[0] = 4.7;
• An array can be initialized directly with elements
14
ArrayList
• ArrayList is a class.
• More sophisticated than arrays.
• Arrays are ideal for organizing fixed number elements
• Like any other collection, ArrayList needn’t be sized in advanced .
ArrayList students = new ArrayList();
• When an item is added, it automatically grows in size, and as item is removed,
the collection will shrink accordingly.
Students.add(new Student())
• Following inserts the specified element at the nth position in the list, shifting
all subsequent items over
void add(int n, E element):
Forexample: arrlist.add(2,25);// inserts 25 on 3rd position
15
ArrayList
16
ArrayList
Iterating Through ArrayLists
for (type referenceVariable : collectionName) {
// Pseudocode. manipulate the referenceVariable as desired
}
17
HashMap
• Java HashMap is a class of dictionary (or map) type collection—that is, a
HashMap gives us direct access to a given object based on a unique key
value.
• Both the key and the object itself can be declared to be of any type.
• It contains only unique elements.
• It may have one null key and multiple null values.
• It maintains no order.
18
HashMap
19
HashMap
boolean containsKey(Object key)
Object remove(Object key)
boolean containsValue(Object value):
20
TreeMap
• The Java TreeMap class is another dictionary type collection.
• TreeMaps are very similar to HashMaps, with one notable difference:
• When we iterate through a TreeMap, objects are automatically
retrieved from the collection in ascending key (sorted) order.
• Dictionaries can use any object type as a key. However, if we use a user-
defined type as a key in TreeMap, the burden is on us to
programmatically define what it means to sort that object type.
21
HashSet
• It is a class use to create a collection that uses a hash table for
storage.
• It implements the Set interface.
• HashSet contains unique elements only
HashSet<String> fruitSet=new HashSet<String>();
fruitSet.add(“Apple");
fruitSet.add(“Mango");
fruitSet.add(“Cherry");
22
Same Object in Multiple Collections
• Inserting an object into a
collection means that a reference
to the object is added.
• This implies that the same object
can be referenced by multiple
collections simultaneously.
• If a given collection is emptied,
then the objects of collection will
not be garbage collected unless
there are no longer any handles
on a given object, then memory
will be recycled by the JVM.
23
Inventing Our Own Collection Types
• We have several ways to create our own collection types:
– Approach #1: We can design a brand-new collection class from scratch.
– Approach #2: We can extend a predefined collection class.
– Approach #3: We can create a “wrapper” class that encapsulates one of
the built-in collection types, to “abstract away” some of the details
involved with manipulating the collection.
24
Using Collection
Collection as Return Type
• Method having a return type as a collection type, can return an arbitrarily
sized collection of object references. Collections can also be passed as
arguments to methods.
public ArrayList<Student> getRegisteredStudents() {
return enrolledStudents;
}
Collections of Derived Types
• If a collection is declared to hold objects of a given superclass then objects
of any type derived from superclass can also be added in the collection.
25