Professional Documents
Culture Documents
Chapter Six
Data Structure and Collection Framework
1. Data Structure
2. Java Collections and Examples
1. Data Structure
A data structure is a particular way of organizing data items apearning in a group and along with
set of operation which can be performed. For example, we can store a list of items having the
same data-type using the array data structure. The idea is to reduce the space and time
complexities of different tasks.
Data Structure=Related Data+Allowed operations on them
Operations include storage, serarching, insertion and delete
ArrayList
Java ArrayList class uses a dynamic array for storing the elements.It extends AbstractList
class and implements List interface.
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow.
Example
import java.util.*;
public class LISTExample
{
public static void main(String args[]){
ArrayList<String> book = new ArrayList<String>();
//creating arraylist and adding object in arraylist
book.add("Java");
book.add("C#");
book.add("C++");
book.add("PHP");
book.add("Python");
for (String st : book){
System.out.println (st);
}
System.out.println ("Count " + book.size());
book.remove("Python");
for (String st : book){
System.out.println (st);
}
System.out.println ("Count " + book.size());
}
}
User-defined class objects in Java ArrayList
class Student{
private int rollno;
private String name;
private int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public String toString(){
return rollno+" "+name+""+age;
}
}
Page 2
TRUE HOPE Core Java (Java SE)
import java.util.*;
public class ArrlistObj{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Mg Mg",23);
Student s2=new Student(102,"Ko Ko",21);
Student s3=new Student(103,"Ma Ma",25);
Remark
iterator is used to get value stored in collection.
it has three methods.
1. hasNext()-return true if iterator has more element (return false if next() throws exception)
2. next() - return the next element,it throw NoSuchElementException.
3. remove() -Removes from the underlying collection the last element returned by the iterator
(optional operation). This method can be called only once per call to next.
2. LinkedList
Java LinkedList class uses doubly linked list to store the elements
Java LinkedList class can contain duplicate elements.
Java LinkedList class maintains insertion order.
In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
LinkedList elements are not stored in contiguous locations like arrays, they are linked with
each other using pointers. Each element of the LinkedList has the
reference(address/pointer) to the next element of the LinkedList.
import java.util.LinkedList;
Page 3
TRUE HOPE Core Java (Java SE)
book.removeFirst();
System.out.println("After removing first element");
for (String st : book){
System.out.println (st);
}
}
}
Vector
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
import java.util.Vector;
public class VectorExample
{
public static void main(String arg[])
{
Vector vec = new Vector ();
vec.addElement("Mg Mg");
vec.addElement(20);
vec.addElement(10000.05);
System.out.println("element: " + vec);
}
}
-----------------------------------------------------------------------------
Set
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set
abstraction.
HashSet
- It holds data item access faster and but that is no ordering.
import java.util.HashSet;
public class HashSetExample {
public static void main(String arg[]) {
HashSet<String> set = new HashSet<String>();
set.add("zero");
set.add("zero");
set.add("one");
set.add("two");
set.add("three");
set.add("four");
System.out.println("element: " + set);
}
}
LinkedHashSet
LinkedHashSet behaves the same as HashSet and Ordering items. The performance of a
LinkedHashSet is likely to be a little slower than a HashSet because of the overhead of
maintaining the linked list structure.
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String arg[]) {
LinkedHashSet<String> set = new LinkedHashSet<String>();
set.add("zero");
set.add("one");
set.add("two");
set.add("three");
set.add("four");
System.out.println("element: " + set);
}
}
Page 4
TRUE HOPE Core Java (Java SE)
TreeSet
If you need a SortedSet, you can use treeSet, which stores its contents in a tree structure that is
kept balanced. This means that the time required to modify or search the tree is .
import java.util.TreeSet;
public class TreesetExample {
public static void main(String arg[]) {
TreeSet<String> set = new TreeSet<String>();
set.add("zero");
set.add("one");
set.add("two");
set.add("three");
set.add("four");
System.out.println("element: " + set);
}
}
---------------------------------------------------------------------------------------------------------------------
The Java Map Classes
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value
at a later date.
Given a key and a value, you can store the value in a Map object. After the value is stored, you
can retrieve it by using its key.
HashMap
HashMap is the implementation of Map, but it doesn't maintain any order.
import java.util.HashMap;
LinkedHashMap
LinkedHashMap<K,V> extends HashMap<K,V> and refines the contract of HashMap by defining an
order to the entries in the map. Linked hashmap gurantees order of elements. Elements are
retrieved in same order they are inserted.
import java.util.LinkedHashMap;
public class LinkedHashMapExample {
public static void main(String arg[]) {
LinkedHashMap<String,Double> balance = new LinkedHashMap<String,Double>();
balance.put("Tom", new Double(3434.34));
balance.put("Peter", new Double(123.22));
balance.put("Mary", new Double(1378.00));
balance.put("Daisy", new Double(99.22));
balance.put("John", new Double(19.08));
for(double str : balance.values()){
System.out.println(str);
}
System.out.println("John's Balance="+balance.get("John"));
}
}
Page 5
TRUE HOPE Core Java (Java SE)
TReeMap
The TReeMap class implements SortedMap, keeping its keys sorted in the same way as TReeSet.
Sorted Map maintains sorted order of keys in a map.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String arg[]) {
TreeMap<String,Double> balance = new TreeMap<String,Double>();
balance.put("Tom", new Double(3434.34));
balance.put("Peter", new Double(123.22));
balance.put("Mary", new Double(1378.00));
balance.put("Daisy", new Double(99.22));
balance.put("John", new Double(19.08));
for(double str : balance.values()){
System.out.println(str);
}
}
}
----------------------------------------------------------------------------------------------------------------------
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines
the default constructor, which creates an empty stack. Stack includes all the methods defined by
Vector, and adds several of its own.To put an object on the top of the stack, call push(). To
remove and return the top element, call pop().
import java.util.Stack;
Page 6
TRUE HOPE Core Java (Java SE)
Returns the element at the head of the queue and removes it or throws exception
remove()
if the queue is empty
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
queue.add("John");
queue.add("Mary");
queue.offer("Tom");
queue.offer("Peter");
Page 7
TRUE HOPE Core Java (Java SE)
Generic Methods
A generic method can declare method-specific generic parameters. These parameters can be used
in the method header or body. An open method has type parameters, which are nonspecific. A
closed method has type arguments, whereas specific types are substituted for type parameters.
public class GenericMethodExample{
public static void main(String args[]) {
Integer[] IntArray={10,20,30,40,50};
Print(IntArray);
String[] StringArray={"Hello","World"};
Print(StringArray);
}
public static <T> void Print(T[] param)
{
for (T element : param)
{
System.out.println("Data" + element);
}
}
}
----------------------------------------------------------------------------------------------------------------------
Using Generic Class
Generic classes encapsulate operations that are not specific to a particular data type. The most
common use for generic classes is with collections like linked lists, hash tables, stacks, queues,
trees, and so on. Operations such as adding and removing items from the collection are performed
in basically the same way regardless of the type of data being stored.
public class GenericClass<T> {
private T element;
public void setElement(T value)
{
element=value;
}
public T getElement(){
return element;
}
}
-----------------------------------------------------------------------------
class GenericDemo {
public static void main(String args[])
{
GenericClass<Integer> gc = new GenericClass<Integer>();
gc.setElement (100);
System.out.println(gc.getElement());
Page 8
TRUE HOPE Core Java (Java SE)
Exercise
1. What is collection?
A collection is a container which holds group of objects. Collection provides a way to manage
objects easily. Collections manages group of objects as single unit. Examples include list of
strings, integers etc. Here are few basic operations we do on collections :
1) Adding objects to collection.
2) Removing or deleting objects from collection.
3) Retrieving object from collection.
4) Iterating collection.
4. What is vector?
Vector is similar to arraylist used for random access. Vector is a dynamic array like arraylist.
Vector size increases or decreases when elements are added and removed. Vector is synchronized.
Page 9
TRUE HOPE Core Java (Java SE)
6. Define Iterator and methods in Iterator?
If we want to iterate through all the elements in collection we use Iterator. Iterator is a standard
way to access elements one by one in collection. Iterator is an object associated with collection
used to loop through the collection. Steps for accessing elements in Iterator :
1) Obtain Iterator object by calling iterator() method on collection.
ArrayList <String> al=new ArrayList<String>();
Iterator itr=al.iterator();
2) Call hasNext() method on iterator object in loop as long as hasNext() returns true.
while(itr.hasNext())
{
}
3) Get each element by calling next() inside the loop.
while(itr.hasNext()){
String str=itr.next();
}
11. Write a Java program to create a new array list, add some elements (string) and print out the
collection.
12. Write a Java program to add some prices of menu for a restaurant and search require menu
price and print that menu price using map.
Key is menu name and value is price.
Page 10