Docsity

Collections, Array List - Web Design and Development - Lecture Slides, Slides of Web Design and Development

Partial preview of the text

Download Collections, Array List - Web Design and Development - Lecture Slides and more Slides Web Design and Development in PDF only on Docsity!

Web Design & Development

Lecture 6

Collections

Collection Design

 All classes provides almost same methods

 get(), size(), isEmpty()…

 Easy learning curve for using Collections

 Implemented as reference to Object

 Similar to using a void * in C

 Require a cast back (down casting) to the actual type

 Example  String element = (String)arraylist.get(i)

 Remember, Java checks all casts at run-time

Collection Messages

 Basic messages

 constructor()
 Creates a collection with no elements
 int size()
 Number of elements in the collection
 boolean add()
 Add a new reference/element at the end of the
collection
 Returns true is the collection is modified.
 iterator()
 Returns an Iterator Object

ArrayList

ArrayList

 Replaces the “Vector”

 Can grow over time

 Methods

 add(Object)  Can add all kinds of objects  implicit upcasting  int size()  Object get(int index)  Index is from 0 to size() -  Must cast to appropriate type when used.  remove(index)  Removes object reference at the specified index  iterator()  We’ll see an example!

Example TestArrayList. java

//checking whether arraylist contains student objects 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); }

// continue..

Example TestArrayList. java

//using loop to iterate for (int i=0; i< al.size(); i++) { Student s = (Student) al.get(i); s.print(); }

} //end of main }

HashMap

HashMap

 Stores key & value in pair form

 Cannot contain duplicate keys

 Implements the Map interface

 Keys and Values are stored as Objects

 put(Key, Value)  implicit upcasting

 Object get(Key)  Must cast to appropriate type when used.

 int size()

Example TestHashMap. java

boolean b = h.isEmpty();

if (b == true){ System.out.println("hashmap is empty"); } else { int size = h.size(); System.out.println("hashmap size:"+ size); }

Student s = (Student) h.get("two"); s.print();

} //end of main }

Compile & Execute

We have learned So far

 How to Perform IO

 Selection and Control Structures

 OOP

 Collections

 So, lets do a small problem

Problem

Address Book

 Wants to store name, address, phone no of a Person

 Features

 Add
 Delete
 Search (on name)
 Exit (from application)

 The above listed features must be available to user in

the form of JOptionPane based MENU.