Java Collections Framework (JCF) in Java Tutorial for students of universities Author: Oxana Dudnik.

Презентация:



Advertisements
Похожие презентации
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
Advertisements

Практическое программирование на Java к.ф.-м.н. Козлов Дмитрий Дмитриевич Кафедра АСВК, Лаборатория Вычислительных комплексов.
1/27 Chapter 9: Template Functions And Template Classes.
© Luxoft Training 2013 Java Collections Framework.
Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.
BREADTH FIRST TRAVERSAL Lesson Plan -3. Evocation.
Абстрактные типы данных 1. Абстрактная дата Date dt1, dt2; dt1 = new Date(1, Date.MARCH, 2006); dt2 = (Date)dt1.clone(); dt2.add(300); //
Unit II Constructor Cont… Destructor Default constructor.
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
1 © Luxoft Training 2012 Inner and anonymous classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Test 10 Вопрос 1. public class Test implements Iterator { // 1 private List list = new ArrayList (); // 2 public void addList(T... ts) { Collections.addAll(list,
1/30 Chapter 8: Dynamic Binding And Abstract classes.
Коллекции Макаревич Л. Г.. Что такое коллекции Коллекция – это объект для хранения множества объектов в одном месте. Это контейнер, куда можно поместить.
1Georgiy KorneevJava Advanced / Новые возможности Java 5 Проблема 1 Метод void dump(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { Object.
© 2006 Cisco Systems, Inc. All rights reserved. MPLS v Complex MPLS VPNs Using Advanced VRF Import and Export Features.
© 2006 Cisco Systems, Inc. All rights reserved. MPLS v MPLS VPN Implementation Configuring VRF Tables.
PAT312, Section 21, December 2006 S21-1 Copyright 2007 MSC.Software Corporation SECTION 21 GROUPS.
Транксрипт:

Java Collections Framework (JCF) in Java Tutorial for students of universities Author: Oxana Dudnik

Hierarchy of Collection Framework

Methods of Collection interface 1. public boolean add(Object element)is used to insert an element in this collection. 2. public boolean addAll(collection c)is used to insert the specified collection elements in the invoking collection. 3. public boolean remove(Object element)is used to delete an element from this collection. 4. public boolean removeAll(Collection c)is used to delete all the elements of specified collection from the invoking collection. 5. public boolean retainAll(Collection c)is used to delete all the elements of invoking collection except the specified collection. 6. public int size()return the total number of elements in the collection. 7. public void clear()removes the total no of element from the collection. 8. public boolean contains(object element)is used to search an element. 9. public boolean containsAll(Collection c)is used to search the specified collection in this collection. 10. public Iterator iterator()returns an iterator. 11. public Object[] toArray()converts collection into array. 12. public boolean isEmpty()checks if collection is empty. 13. public boolean equals(Object element)matches two collection.14public int hashCode()returns the hashcode number for collection.

Methods of Iterator interface public boolean hasNext() it returns true if iterator has more elements. public object next() it returns the element and moves the cursor pointer to the next element. public void remove() it removes the last elements returned by the iterator. It is rarely used.

Java ArrayList class 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 class is non synchronized. Java ArrayList allows random access because array works at the index basis. In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.

non-generic example of creating java collection. ArrayList al=new ArrayList();//creating old non- generic arraylist new generic example of creating java collection. ArrayList al=new ArrayList ();//c reating new generic arraylist

import java.util.*; class TestCollection1{ public static void main(String args[]){ //creating array list ArrayList al=new ArrayList (); al.add("Ravi");//adding object in arraylist al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); //getting Iterator from arraylist to traverse elements Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); }

import java.util.*; class TestCollection2{ public static void main(String args[]){ ArrayList al=new ArrayList () ; al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); for(String obj:al) System.out.println(obj); }

Java LinkedList class Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces. Java LinkedList class can contain duplicate elements. Java LinkedList class maintains insertion order. Java LinkedList class is non synchronized. In Java LinkedList class, manipulation is fast because no shifting needs to be occurred. Java LinkedList class can be used as list, stack or queue.

Java HashSet class uses hashtable to store the elements.It extends AbstractSet class and implements Set interface. contains unique elements only.

Difference between List and Set: List can contain duplicate elements whereas Set contains unique elements only.

Java LinkedHashSet class: contains unique elements only like HashSet. It extends HashSet class and implements Set interface. maintains insertion order.

Java Map Interface A map contains values based on the key i.e. key and value pair.Each pair is known as an entry.Map contains only unique elements. Commonly used methods of Map interface: public Object put(object key,Object value): is used to insert an entry in this map. public void putAll(Map map):is used to insert the specified map in this map. public Object remove(object key):is used to delete an entry for the specified key. public Object get(Object key):is used to return the value for the specified key. public boolean containsKey(Object key):is used to search the specified key from this map. public boolean containsValue(Object value):is used to search the specified value from this map. public Set keySet():returns the Set view containing all the keys. public Set entrySet():returns the Set view containing all the keys and values.

Java HashMap class A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class. It contains only unique elements. It may have one null key and multiple null values. It maintains no order.

What is difference between HashSet and HashMap? HashSet contains only values whereas HashMap contains entry(key and value).

Java Hashtable class A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class. It contains only unique elements. It may have not have any null key or value. It is synchronized.

import java.util.*; class TestCollection3{ public static void main(String args[]){ Hashtable hm=new Hashtable (); hm.put(100,"Amit"); hm.put(102,"Ravi"); hm.put(101,"Vijay"); hm.put(103,"Rahul"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); }

Difference between HashMap and Hashtable

Static Methods on Collections Search and sort: binarySearch(), sort() Reorganization: reverse(), shuffle() Wrappings: unModifiableCollection, synchonizedCollection

Method of Collections class for sorting List elements public void sort(List list): is used to sort the elements of List.List elements must be of Comparable type.

Comparable interface Syntax: public int compareTo(Object obj): is used to compare the current object with the specified object.

class Student implements Comparable{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } public int compareTo(Object obj){ Student st=(Student)obj; if(age==st.age) return 0; else if(age>st.age) return 1; else return -1; }

Comparator interface Syntax of compare method public int compare(Object obj1,Object obj2): compares the first object with second object.

import java.util.*; class NameComparator implements Comparator { public int Compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; return s1.name.compareTo(s2.name); } Usage: Collections.sort(arrayList,new NameComparator ());

Tests al=92http:// al=92