collections framework

23
Collections frame work The process of storing the data in the memory is known as data structures. In which either can store the data or search the data or sort the data very efficiently. In java language data structures can be handled by using “collection frameworks” If any object is collection of heterogeneous objects is known as “collection object”. Every collection object is depends on a class known as collection class, collection of collection classes is known as “collection frameworks”. The main aim of collection frameworks is to manage the data of heterogeneous classes very efficiently in the memory location. Collection framework mainly depends on 3 interfaces. 1. list interface 2. Set interface 3. Map interface. List interface:-

Upload: anand-buddarapu

Post on 14-Aug-2015

8 views

Category:

Education


3 download

TRANSCRIPT

Page 1: Collections framework

Collections frame work

The process of storing the data in the memory is known as data structures. In which either can store the data or search the data or sort the data very efficiently.

In java language data structures can be handled by using “collection frameworks”

If any object is collection of heterogeneous objects is known as “collection object”.

Every collection object is depends on a class known as collection class, collection of collection classes is known as “collection frameworks”.

The main aim of collection frameworks is to manage the data of heterogeneous classes very efficiently in the memory location.

Collection framework mainly depends on 3 interfaces.

1. list interface2. Set interface3. Map interface.

List interface:-

It is a predefined interface in java.util.pacakge, and which was implemented in the following classes.

1. Stack2. Array list3. Vector4. Linked list

The main aim of the list interface is accept duplicate values. i.e.by creating object of any list interface classes we can able to store any heterogeneous values with repetition.

Page 2: Collections framework

Set interface:-

it is a predefined interface in java.util.pacakge, implemented in the following classes

1. HashSet2. Linked HashSet

The main aim of the set interface is to accept unique values in the memory i.e. the objects of set interface implemented classes, can accept non repetition values.

3. Map interface:-

It is a predefined interface in java.util.pacakge and it is implemented in the following classes

1. HashMap2. HashTable

The main aim of the map interface is used to store data in the form of key value pairs, in this scenario key should be the unique value, value can be any duplicate data or repeated data.

Retrieving of data from collection object:-

The data from any collection object can be retrieved using following 4 techniques.

1. For-each loop2. Iterator interface3. List IteratorInterface4. Enumerator

Note:

Page 3: Collections framework

The classes which are derived from list, set, map are technically known as collection classes, the objects which are created for these classes are known as collection objects.

For each loop:-

This is similar to “for loop”. Which will execute multiple times. Whenever the collection object contains list of values otherwise the for each loop will be terminated.

Syntax:

For(data type variable : collection object)

{

--

--

--

}

In the above syntax collection object can be object of any collection class, it returns a value whenever it contains list of data in its memory. If no values are available or control reaches to end of collection object memory then it returns null value so that collection will be failed in for each loop.

Iterator interface:-

This is alternative mechanism to retrieve the values from the collection object, it mainly contains following methods

1. hasNext()2. next()

Page 4: Collections framework

hasNext():-

it is a predefined method used to check whether any value available in the location in the next location of collection object if any element is existing returns true otherwise false.

Next():-

Returns next element in the collection object.

Note

By using iterator interface we can retrieve the data only by searching in the forward direction (from left to right)

While (iterator object.hasnext())

{

Sop(iterator object.next();

}

ListIterator interface:-

It is similar to iterator interface can be used to retrieve the data either in forward direction or backword direction.

Mainly it contains following methods.

hasNext():-

it is predefined method returs true in the listiterator has more elements when transeversing the list in the forward direction

Next();

Page 5: Collections framework

Which returns next element which is available in the list.

hasPrevious():

it returns true if the list iterator has more elements when traversing the list in the reverse direction

Previous():

It is predefined method returns the previous element in the list

Creation of collection object:-

For any type of collection class we must use following syntax to create an object.

Collection class<tamplate> obj=new collection class <tamplat> ();

In the above syntax collection class can be any implemented class of list/set/map interfacesTemplate can be any wrapper class, based on which the sufficient memory will be allocated and the related data will be accepted.

Ex:-Stack<String> s=new stack <String>();In the above syntax stack is a collection class and whose object can hold only string values.

List interface implemented classes:-1.ArrayList:-It is a predefined class in java.util.package represents a growable array. That means whose size can be created by designing object for arraylist class.

Arraylist <tamplate> obj=new Arraylist<tamplate>();

ArrayList class contains following methods to performs various operations like insert delete sesarching etc.

Methods of ArrayList():-Add():-

Page 6: Collections framework

It is a performed method can be used to add new element in the Array list and it can be used in two different way.

a.add(element):-which will be add a new element at the end of array list

b. add(index,element):-which will add any element at a specific index values (insertion operaton)

ex:-Arraylist<string> al =new Array list <string>();

Note:-By default 10 memory location are given by arraylist class object. And this can be resized at the execution time.

addAll():-

which can be used to add all the list of one Arraylist elements to another Array list and it can be used I two difference ways.

a. addAll(collection object):

which can be used to add all the elements of given Array list at the end of another Array list.

b. addAll(index, collection):-

which will add values of collection object at a specific index values.

Page 7: Collections framework

Array List < String > al1= new Array list <String>();Al.addAll(al)Al.addAll(3,al)

Remove(); Which can be used to remove an element from the Arraylist and it can be used in 2 different ways

a. remove(element):

which removes an element based on its name

ex:-

al.remove(“india”);

b. remove (index value):-

which will remove an element based on index value.

Ex:- al.remove(1);

c. removeRamnge():-

which can be used to remove list of elements in a given range.

Sysntax:- removeRange(strting index, ending index)

d. clear():-which can be used to remove all the elements in the given arraylist.Ex:- al.clear();

Size():-Which can be used to find the no.of elements in the collecion objects

Page 8: Collections framework

Al.size(); returns no.of elements.

IsEmpty():-It is a boolean method returns true if the array list is empty. Otherwise reutrns false.Al.isEmpty();

indexOf();-which can be used to get the index value of a specific element(always it gives index of first occurrence element).Al.indexOf(“element”);

lastIndexOf():-which can be used to get the index value of the last occurrence element.Al.lastIndexOf(“element”);Get():-Which can be used to retrive an element an element based on index value.Al.get(index value);Contains():-It is a boolean method returns true if the given element is existing in the array list otherwise returns false.Al.contains(“element”);

Clone():-Which can be used to derive one more arraylist from the given existing list with same elements and features.

toArray():-

Page 9: Collections framework

it is a predefined method can be used to convert one arraylist into array. i.e. growable array is converted into normal array so that we cont perform insertion or deletion operationssysntax:- al.toArray();

write a java program to implement arraylist.

Import java.util.*;Class ArrayListDemo{Public static viod main(String []args){ArrayList<string> ar1=new ArrayList<String>();Ar1.add(“c-lang”);Ar1.add(“c++”);Ar1.add(“java”);Ar1.add(“.net”);Ar1.add(“java”);System.out.println(“contents in ar1:”+ar1);Ar1.add(2,”android”);System.out.println(“contents after adding in ar1:”+ar1);System.out.println(“…………….”);System.out.println(“contents at first index ar1:”+ar1.get(1));System.out.println(“…………”);Ar1.remove(3);Ar1.remove(“c++”);System.out.println(“content after removing in ar1:”+ar1);System.out.println(“size of arrayList:”+ar1.size());System.out.println(“extrcting using for each loop”);For (string j:ar1)

Page 10: Collections framework

{System.out.println(j);}ArrayList<string> ar2=new ArrayList<String>();arl2.addAll(ar1);System.out.println(“content in ar1:”+ar1);Ar1.clear();System.out.println(“content in ar1:”+ar1);}}

Vector class:-Which is also similar to array list class but the main difference is vector is sysnchronized and arraylist is unsysncronized.i.e. arraylist object can be shared by multiple threds at a time only.where as vector class object is not sharable by multiple threads at a time

Stack class:-It is a predifined class in java.util.package mainly works on LIFO (last in first out) mechanism i.e. in which whatever the elements we are added first which can be retrived and removed at last.A stack memeory can be created by creating an object for that classStack<string> ar1=new Stack<String>();

Following methods can be used ti perform various oprations.

Page 11: Collections framework

Empty():-Returns true if the stack is empty otherwise returns falsePeek():-Looks at the element at the top of the stack without removing it form the stackPush():-Which can be used to push an item into the top of stack.Pop():-Which can be used to rmove an element from top of the stack and it reurns the removed element.Search():-It is a predefined method in stack class used to search an element in the given stack it returns -1 if no element is found otherwise returns any positive vslue index value.

Linked list():-It is a predefined class in java.util.package can be used to perform various oprations on linked list. This linked list class supports doubdly linked list

to create a linked list we must create an object with following syntax.Linkedlist<template> obj=new LinkedList<template>();

linked list class offering various opeations to perform diff operations like adding new element, removing existing element, searching of an element etc..

note: refer java Api to get the complete methods list of stack vector and linked list along with Arraylist.

Set interface imolementaion class:-

Page 12: Collections framework

HashSet():-It is a predefined class in java.util.package. can be used to perform various operations like add remove search of objects or elements in the collection object. memeory location of hashset collection class and it is offereing following methods Add(), clear(), clone(), contains(), isEmpty(), iterator(), remove(), size().Note:- the above methods can be used to similar Arraylist.

Iterator():-Which returns an “iterator object” accepts only forwarding traverse over the elements in the set.HashSet can be created with the following syntax.Hash<tamplate> obj=Hash<template>();

Note:- HashSet class does not allows duplicate values ans its values will never be stored in a sequencial order.

Write a program to implement HashSet….Import java.util.*;Class HashSetEx{Public static void main(string[] args){HashSet<string> hs=new HashSet<String>();Hs.add(“india”);Hs.add(“America”);Hs.add(“japan”);Hs.add(“china”);System.out.println(“HashSet:=”+hs);

Page 13: Collections framework

Hs.add(“America”);System.out.println(“HashSet:=”+hs);Iterator it=hs.iterator();System.out.println(“elements using iterator”);While(it.hashnext()){System.out.println(it.next());}}}

Output:Javac HashSetEx.javaJava HashSetExHashSet=[America, chaina, japan, india]Hashset=[America, chaina, japan, india]Elements using iterator:AmericaChinaJapanIndia

Note: hashSet Class is not thread safe of unsychronized ie whose object is shareble by multiple threads simultaneously

LinkedHashSet Class:-linkedHasSet is similor to Hashset class available in java.util package can be used to perform various operations on collection objects like adding removing searching etc.

Page 14: Collections framework

the main difference b/w Hashset and LinkedHashSet is HashSet is unsynchronized where as linkedHashSet is synchronized ie. The object of linkedHashset is used by one thread then it doesnot allow other thread to working on same object

linnedHashSet is created by following syntaxlinkedHashSet<template> obj=new LinkedHashSet<template>();note: the elements of HashSet are not stored in sequence order wher as the elements of linkedHashSet are stored in sequence order.

Map Interface implementation classes:-HashMap:

It is a predefined class which can be used to store heterogenious values in the form of (key, value) pairs, key should be unique value where as value can be duplicate.

To create HashMap we must use the following sysntaxHashMap<template,tamplate1>obj=newHashMap<tamplate,tamplate1>();

HashMap class offering various predefined methods to perform different operations like insertion, deletion, searching etc

Put():-Which can be used to store a (key, value) Pair in the collection object.

Get():-Which can be used to get the value from the collection object based on key value

Page 15: Collections framework

Remove():-Which can be used to remove a value along with key from collection object based on key valueNote:- refer java Api for other methods

Writer a program to implement HashMap….

Import java.util.*;Class HashMapDemo{Public static void main(string[] srgs){HasMap<string, long>= new HashMap<string, long>();String name,str;Long phno;Scanner s=new Scanner(system.in); While(true)System.out.println(“………………….”);System.out.println(“1-Enter phone number”);System.out.println(“2-look up in the book”);System.out.println(“3-Display names in book”);System.out.println(“4-Exit”);System.out.println(“enter your choice”);Int n= s.nextInt();Seitch(n){Case:system.out.println(“enter name:”);Name=s.next();System.out.println(“Enter phone number”);Phno=s.nextLong();

Page 16: Collections framework

Hm.put(name,phno);Break;Case2: system.out.println(“enter name:”);Names=s.next();Name=name.trim();Phno=hm.get(name);System.out.println(“Enter phone number”+phno);Break;Case3: set<string> s1=new HashSet<string>();S1=hm.keyset();System.out.println(s1);Break;Case4: return;}}}HashTable:-It is a predefined class in java.util package similor to HashMap class can be used to strore the collection of objects..

The main difference b/w HashMap and HashTable is HashMap is unsysnchronized(not thread safe) where hashTable is sysnchronized.

Page 17: Collections framework

}}