You are on page 1of 10

TRUE HOPE Core Java (Java SE)

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

Need of Data Structures


As applications are getting complexed and amount of data is increasing day by day, there may
arrise the following problems:
Data Search: Consider an inventory size of 1000 items in a store, If our application needs to
search for a particular item, it needs to traverse 1000 items every time, results in slowing down
the search process.
Multiple requests: If thousands of users are searching the data simultaneously on a web server,
then there are the chances that a very large server can be failed during that process
In order to solve the above problems, data structures are used. Data is organized to form a data
structure in such a way that all items are not required to be searched and required data can be
searched instantly. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
2. Java Collections and Examples
The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects. Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces
 Set
 List
 Queue
 Deque
Classes
 ArrayList
 Vector
 LinkedList
 HashSet
 LinkedHashSet
 TreeSet
Page 1
TRUE HOPE Core Java (Java SE)
Framework Interface

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);

ArrayList<Student> al=new ArrayList<Student>();//creating arraylist


al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
Iterator itr=al.iterator(); //traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.toString());
}
}
}

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;

public class LinkedListExample {


public static void main(String args[]){
LinkedList<String> book = new LinkedList<String>();
book.add("Java");
book.add("C#");
book.add("C++");
book.add("PHP");
book.add("Python");
book.addFirst("VB");
book.add(2, "HTML");
System.out.println("All element");
for (String st : book){
System.out.println (st);
}

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;

public class HashMapExample {


public static void main(String args[])
{
HashMap mp = new HashMap();
mp.put("Java", "Java OOP");
mp.put("C#", "C Sharp");
mp.put("VB", "Visual Basic .NET");
mp.put("PY", "Python");
System.out.println(" Map Elements");
System.out.print(mp);
//System.out.println(" Map Require Elements");
System.out.println("Key VB="+mp.get("VB"));
}
}
}

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;

public class StackDemo {


public static void main(String[] args) {
Stack st = new Stack();
// Add data
st.push("Java");
st.push("Source");
st.push("code");
// removing top object
System.out.println("Removed object is: "+st.pop());
// elements after remove
System.out.println("Elements after remove: "+st);
}
}
Queue Basics
A queue is a data structure in which you can line up objects and remove them as and when
needed, for example consider of queue of travellers standing in a line to buy a bus ticket they are
typicall processed in the order in which they join the queue i.e the first one get to use the ticked
window first, the second one uses the ticket window second and so on. Queues are mostly FIFO
"First In First Out" and we will limit our discussion to FIFO Queue.
A Queue in Java is just an interface. LinkedList class implements the Queue interface and
therefore it can be used as a Queue.

The table below summarizes some standard operation in a Queue.


Method Purpose
Returns the element at the head of the queue or returns null if the queue is
peek()
empty
Returns the element at the head of the queue and removes it or returns null if the
poll()
queue is empty
Returns the element at the head of the queue or throws exception if the queue is
element()
empty

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

offer(Object o) Inserts an objects at the tail of the queue if possible

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");

System.out.println("remove: " + queue.remove());


System.out.println("remove: " + queue.remove());
System.out.println("element: " + queue.element());
System.out.println("poll: " + queue.poll());
System.out.println("peek: " + queue.peek());
System.out.println("remove: " + queue.remove());
}
}
--------------------------------------------------------------------------------------------------------------------
Enumeration
The Enumeration interface isn't itself a data structure, but it is very important within the context of
other data structures. The Enumeration interface defines a means to retrieve successive elements
from a data structure.
For example, Enumeration defines a method called nextElement that is used to get the next
element in a data structure that contains multiple elements.
The methods declared by Enumeration are summarized in the following table:
No. Methods with Description
1 boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to
extract, and false when all the elements have been enumerated.
2 Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.
Example
Following is an example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements(); //save vector object to enumeration object
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}

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());

GenericClass<String> st = new GenericClass<String>();


st.setElement ("Java");
System.out.println(st.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.

2. Explain about ArrayList?


ArrayList is an ordered collection which extends AbstractList and implements List interface. We
use ArrayList mainly when we need faster access and fast iteration of elements in list. We can
insert nulls in to arraylist. Arraylist is nothing but a growable array.
1) Faster and easier access.
2) Used for Random access of elements.
3) We cannot insert or delete elements from middle of list.

3. Difference between Array and ArrayList?


Arrays are used to store primitives or objects of same type or variables that are subclasses of same
type. ArrayList : It is an ordered collection which grows dynamically. In list we can insert nulls
values and list allows duplicate elements.
ARRAY ARRAY LIST
1) While creating array we have to know the 1) But it is not required to know size while
size. creating ArrayList, because arraylist grows
dynamically.
2) To put an element in to array we use the 2) We can add element to arraylist with
following syntax :String array[] = new following
String[5];array[1] = “java”;We must know syntax :List<String> stringList = new
specific location to insert an element in to ArrayList<String>();stringList.add(“java”);
array. If we try to put element in index which is
out of range we get ArrayIndexOutOfBounds
Exception
3) Arrays are static 3) ArrayList is dynamic
4) We can store objects and primitives 4) We can store only primitives prior to 1.5 .
From1.5 we can store even objects also.
5) We have to manually write logic for 5) Just a method call would add or remove
inserting and removing elements. elements from list.
6) Arrays are faster 6) Arraylist is slower.

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.

5. Difference between arraylist and vector?


Both ArrayList and vector grows dynamically. The differences between arraylist and vector are:
1) Arraylist is not synchronized and 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();
}

7. Explain about Sets?


A set is a collection which does not allow duplicates. Set internally implements equals() method
which doesn’t allow duplicates.Adding an duplicate element to a set would be ignored. Set
interface is implemented in java.util.set package.Set interface does not have any additional
methods . It has only collection methods. A set can contain atmost one null value. ArrayList is an
ordered collection.In arraylists order remains same in which they are inserted. But coming to set it
is an unordered collection.

8. Implementations of Set interface?


1) HashSet
2) Linked HashSet
3) TreeSet

9. Explain about Map interface in java?


A map is an association of key-value pairs. Both keys and values in map are objects. Maps cannot
have duplicate keys but can have duplicate value objects.

10. Difference between arraylist and linkedlist?


Arraylist LinkedList
Implements RandomAccess interface we can It extends Abstract sequential List interface
search randomly all the elements in the list. which provides sequential access to elements.
Searching and retrieval of elements is fast Searching and retrieval of elements is slow
since arraylist provides random access. because of sequential access to elements.
Adding and removal of elements in random Adding and removal of elements in random
positions is slow.For example if we want to add positions is fast because there is no need of
element to middle of the list we have to move resizing the array just by updating the node
the elements in the list and then we need to structures with new addresses.
insert the element. Similarly for removing the
element we need to follow the same thing.

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

You might also like