ZeePedia

JAVA: Collections

<< JAVA: Inheritance
JAVA: Intro to Exceptions >>
img
Web Design & Development ­ CS506
VU
Lesson 6
Collections
A collection represents group of objects know as its elements. Java has a built-in support for collections.
Collection classes are similar to STL in C++. An advantage of a collection over an array is that you
don't need to know the eventual size of the collection in order to add objects to it. The java.util package
provides a set of collection classes that helps a programmer in number of ways.
Collections Design
All classes almost provides same methods like get(), size(), isEmpty() etc. These methods will return
the object stored in it, number of objects stored and whether collection contains an object or not
respectively.
Java collections are capable of storing any kind of objects. Collections store references to objects. This is
similar to using a void* in C. therefore down casting is required to get the actual type. For example, if
string in stored in a collection then to get it back, we write
String element = (String)arraylist.get(i);
Collection messages
Some basic messages (methods) are:
Constructor
-- creates a collection with no elements
int size()
-- returns the number of elements in a collection
boolean add(Object)
-- adds a new element in the collection
-- returns true if the element is added successfully false otherwise
boolean isEmpty()
-- returns true if this collection contains no element false otherwise
boolean contains(Object)
-- returns true if this collection contains the specified element by using iterative search
boolean remove(Object)
-- removes a single instance of the specified element from this collection, if it is present
ArrayList
It's like a resizable array. ArrayList actually comes as a replacement the old "Vector" collection. As
we add or remove elements into or from it, it grows or shrinks over time.
Useful Methods
add (Object)
-- With the help of this method, any object can be added into ArrayList because
Object is the super class of all classes.
-- Objects going to add will implicitly up-cast.
Object get(int index)
39
img
Web Design & Development ­ CS506
VU
-- Returns the element at the specified position in the list
-- index ranges from 0 to size()-1
-- must cast to appropriate type
remove (int index)
-- Removes the element at the specified position in this list.
-- Shifts any subsequent elements to the left (subtracts one from their indices).
int size( )
Example Code: Using ArrayList class
We'll store Student objects in the ArrayList. We are using the same student class which we built in
previous lectures/handouts.
We'll add three student objects and later prints all the student objects after retrieving them from
ArrayList. Let's look at the code
iport java.util.*;
public class ArrayListTest {
public static void main(String[] args) {
// creating arrayList object by calling constructor
ArrayList al= new ArrayList();
// creating three Student objects Student s1 = new Student ("ali" ,
1); Student s2 = new Student ("saad" , 2); Student s3 = new
Student ("raza" , 3);
// adding elements (Student objects) into arralylist al.add(s1);
al.add(s2);
al.add(s3);
// checking whether arraylist is empty or not boolean b = al.isEmpty
();
if (b = = true) {
System.out.println("arraylist is empty");
} else {
int size = al.size();
System.out.println("arraylist size: " + size);
}
// using loop to iterate. Loops starts from 0 to one
// less than size
for (int i=0; i<al.size(); i++ ){
// retrieving object from arraylist
Student s = (Student) al.get(i);
// calling student class print method
40
img
Web Design & Development ­ CS506
VU
s.print();
} // end for loop
} // end main
} // end class
Output
HashMap
Store elements in the form of key- value pair form. A key is associated with each object that is stored.
This allows fast retrieval of that object. Keys are unique.
Useful Methods
put(Object key, Object Value)
-- Keys & Values are stored in the form of objects (implicit upcasting is performed).
-- Associates the specified value with the specified key in this map.
-- If the map previously contained a mapping for this key, the old value is replaced.
Object get(Object key)
-- Returns the value to which the specified key is mapped in this identity hash map, or null
if the map contains no mapping for this key.
-- Must downcast to appropriate type when used
int size( )
Example Code: using HashMap class
In this example code, we'll store Student objects as values and their rollnos in the form of strings as keys.
Same Student class is used. The code is;
iport java.util.*;
public class HashMapTest {
public static void main(String[] args) {
// creating HashMap object
HashMap h= new HashMap();
41
img
Web Design & Development ­ CS506
VU
// creating Student objects
Student s1 = new Student ("ali" , 1); Student s2 = new Student
("saad" , 2); Student s3 = new Student ("raza" , 6);
// adding elements (Student objects) where roll nos
// are stored as keys and student objects as values
h.add("one" , s1); h.add("two" ,
s2); h.add("six", s3);
// checking whether hashmap is empty or not boolean b = h.isEmpty ();
if (b == true) {
System.out.println("hashmap is empty");
} else {
int size = h.size();
System.out.println("hashmap size: " + size);
}
// retrieving student object against rollno two and
// performing downcasting
Student s = (Student)h.get("two");
// calling student's class print method s.print();
} // end main
} // end class
Output
References:
J2SE 5.0 new features: http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
Technical Article: http://java.sun.com/developer/technicalArticles/releases/j2se15/
Beginning Java2 by Ivor Horton
Example code, their explanations and corresponding figures for this handout are taken from the book
JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students
of the course Web Design and Development and not for any other commercial purpose without the
42
img
Web Design & Development ­ CS506
VU
consent of author.
Address Book
Warning: It is strongly advised that you type the code given in this example yourself. Do not copy/paste
it; most probably you will get unexpected errors that you have never seen. Some bugs are
deliberately introduced as well to avoid copy- pasting. TAs will not cooperate with you in
debugging such errors.
Problem
We want to build an address book that is capable of storing name, address & phone number of a
person.
Address book provides functionality in the form of a JOptionPane based menu. The feature list
includes
Add ­ to add a new person record
Delete ­ to delete an existing person record by name
Search ­ to search a person record by name
Exit ­ to exit from application
The Address book should also support persistence for person records
Approach for Solving Problem
Building a small address book generally involves 3 steps. Let us briefly discuss each step and write a
solution code for each step
Step1 ­ Make PersonInfo class
First of all you need to store your desired information for each person. For this you can create a
user-defined data type (i.e. a class). Make a class PersonInfo with name, address and phone
number as its attributes.
Write a parameterized constructor for this class.
Write print method in Person class that displays one person record on a message dialog box.
The code for PersonInfo class is given below.
import javax.swing.*;
class PersonInfo {
String name;
String address;
String phoneNum;
//parameterized constructor
public PresonInfo(String n, String a, String p) {
name = n;
43
img
Web Design & Development ­ CS506
VU
address = a;
phoneNm = p;
}
//method for displaying person record on GUI
public void print( ) {
JOptionPane.showMessageDialog(null, "name: " + name +
"address:" +address + "phone no:" + phoneNum);
}
}
Note: Not declaring attributes as private is a bad approach but we have done it to keep things
simple here.
Step2 ­ Make AddressBook class
Take the example of daily life; generally address book is used to store more than one person
records and we don't know in advance how many records are going to be added into it.
So, we need some data structure that can help us in storing more than one
PersonInfo objects without concerning about its size.
ArrayList can be used to achieve the above functionality
Create a class Address Book with an ArrayList as its attribute. This arraylist will be used to store
the information of different persons in the form of PersonInfo Objects. This class will also
provide addPerson, deletePerson & searchPerson methods. These methods are used for adding
new person records, deleting an existing person record by name and searching among existing
person records by name respectively.
Input/Output will be performed through JOptionPane.
The code for AddressBook class is
import javax.swing.*;
import java.util.*;
class AddressBook {
ArrayList persons;
//constructor
public AddressBook ( ) {
persons = new ArrayList();
}
//add new person record to arraylist after taking input
public void addPerson( ) {
44
img
Web Design & Development ­ CS506
VU
String name = JOptionPane.showInputDialog("Enter name");
String add = JOptionPane.showInputDialog("Enter address");
String pNum = JOptionPane.showInputDialog("Enter phone no");
//construt new person object
PersonInfo p = new PersonInfo(name, add, pNum);
//add the above PersonInfo object to arraylist
persons.add(p);
}
//search person record by name by iterating over arraylist
public void searchPerson (String n) {
for (int i=0; i< persons.size(); i++) {
PersonInfo p = (PersonInfo)persons.get(i);
if ( n.equals(p.name) ) {
p.print();
}
} // end for
} // end searchPerson
//delete person record by name by iterating over arraylist
public void deletePerson (String n) {
for (int i=0; i< persons.size(); i++) {
PersonInfo p = (PersonInfo)persons.get(i);
if ( n.equals(p.name) ) {
persons.remove(i);
}
}
}
} // end class
The addperson method first takes input for name, address and phone number and than construct a
PersonInfo object by using the recently taken input values. Then the newly constructed object is
added to the arraylist ­ persons.
The searchPerson & deletePerson methods are using the same methodology i.e. first they search the
required record by name and than prints his/her detail or delete the record permanently from the
ArrayList.
Both the methods are taking string argument, by using this they can perform their search or delete
operation. We used for loop for iterating the whole ArrayList. By using the size method of ArrayList,
we can control our loop as ArrayList indexes range starts from 0 to one less than size.
45
img
Web Design & Development ­ CS506
VU
Notice that, inside loop we retrieve each PersonInfo object by using down casting operation. After
that we compare each PersonInfo object's name by the one passed to these methods using equal method
since Strings are always being compared using equal method.
Inside if block of searchPerson, print method is called using PersonInfo object that will display person
information on GUI. On the other hand, inside if block of deletePerson method, remove method of
ArrayList class is called that is used to delete record from persons i.e. ArrayList.
Step3 ­ Make Test class (driver program)
This class will contain a main method and an object of AddressBook class.
Build GUI based menu by using switch selection structure
Call appropriate methods of AddressBook class
The code for Test class is
import javax.swing.*;
class Test {
Public static void main (String args[]) {
AddressBook ab = new AddressBook();
String input, s;
int ch;
while (true) {
input = JOptionPane.showInputDialog("Enter 1 to add " +
"\n Enter 2 to Search \n Enter 3 to Delete" +
"\n Enter 4 to Exit");
ch = Integer.parseInt(input);
switch (ch) {
case 1:
ab.addPerson();
break;
case 2:
s = JOptionPane.showInputDialog(
"Enter name to search ");
ab.searchPerson(s);
break;
case 3:
s = JOptionPane.showInputDialog(
"Enter name to delete ");
ab.deletePerson(s);
break;
case 4:
System.exit(0);
}
46
img
Web Design & Development ­ CS506
VU
}//end while
}//end main
}
Note that we use infinite while loop that would never end or stop given that our program should only exit
when user enters 4 i.e. exit option.
Compile & Execute
Compile all three classes and run Test class. Bravo, you successfully completed the all basic three
steps. Enjoy! .
Reference
Entire content for this handout are taken from the book JAVA A Lab Course by Umair Javed. This
material is available just for the use of VU students of the course Web Design and Development and not
for any other commercial purpose.
47