Инфоурок Информатика ПрезентацииWork with Collections in Java.(for students)

Work with Collections in Java.(for students)

Скачать материал
Скачать материал

Описание презентации по отдельным слайдам:

  • Java Collections Framework (JCF) in JavaTutorial for students of universities...

    1 слайд

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

  • 2 слайд

  • Hierarchy of Collection Framework

    3 слайд

    Hierarchy of Collection Framework

  • 4 слайд

  • Methods of Collection interface1.public boolean add(Object element)is used...

    5 слайд

    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 interfacepublic boolean hasNext() it returns true if ite...

    6 слайд

    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 classJava ArrayList class uses a dynamic array for storing th...

    7 слайд

    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(...

    8 слайд

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


    new generic example of creating java collection.
    ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist  


  • import java.util.*;  
class TestCollection1{  
 public static void main(Strin...

    9 слайд

    import java.util.*;  
    class TestCollection1{  
     public static void main(String args[]){  
       //creating array list  

      ArrayList<String> al=new ArrayList<String>();   
    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(Strin...

    10 слайд

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

  • Java LinkedList classJava LinkedList class uses doubly linked list to store...

    11 слайд

    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 classuses hashtable to store the elements.It extends AbstractSe...

    12 слайд

    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 wherea...

    13 слайд

    Difference between List and Set:



    List can contain duplicate elements whereas Set contains unique elements only.

  • 14 слайд

  • Java LinkedHashSet class:contains unique elements only like HashSet. It exte...

    15 слайд

    Java LinkedHashSet class:

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

  • 16 слайд

  • 17 слайд

  • Java Map InterfaceA map contains values based on the key i.e. key and value...

    18 слайд

    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 classA HashMap contains values based on the key. It implements...

    19 слайд

    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 value...

    20 слайд

    What is difference between HashSet and HashMap?



    HashSet contains only values whereas HashMap contains entry(key and value).

  • Java Hashtable classA Hashtable is an array of list.Each list is known as a...

    21 слайд

    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(Strin...

    22 слайд

    import java.util.*;  
    class TestCollection3{  
     public static void main(String args[]){  
       
      Hashtable<Integer,String> hm=new Hashtable<Integer,String>();  
      
      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

    23 слайд

    Difference between HashMap and Hashtable

  • 24 слайд

  • Static Methods on Collections•
Search and sort: 
binarySearch()
, 
sort()

R...

    25 слайд

    Static Methods on Collections


    Search and sort:
    binarySearch()
    ,
    sort()

    Reorganization:
    reverse()
    ,
    shuffle()

    Wrappings:
    unModifiableCollection
    ,
    synchonizedCollection

  • Method of Collections class for sorting List elementspublic void sort(List l...

    26 слайд

    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.

  • 27 слайд

  • Comparable interfaceSyntax:

public int compareTo(Object obj): is used to co...

    28 слайд

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

    29 слайд

    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 interfaceSyntax of compare method

public int compare(Object obj1...

    30 слайд

    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 in...

    31 слайд

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

  • Testshttp://www.javatpoint.com/directload.jsp?val=92

    32 слайд

    Tests
    http://www.javatpoint.com/directload.jsp?val=92

  • 33 слайд

  • 34 слайд

  • 35 слайд

  • 36 слайд

Краткое описание документа:

Java Collection Framework — иерархия интерфейсов и их реализаций, которая является частью JDK и позволяет разработчику пользоваться большим количесвом структур данных из «коробки». Этот интерфейс находится в составе JDK c версии 1.2 и определяет основные методы работы с простыми наборами элементов, которые будут общими для всех его реализаций (например size(), isEmpty(), add(E e) и др.). Интерфейс был слегка доработан с приходом дженериков в Java 1.5. Так же в версии Java 8 было добавлено несколько новых метода для работы с лямбдами (такие как stream(), parallelStream(), removeIf(Predicate<? super E> filter) и др.).

Скачать материал

Найдите материал к любому уроку, указав свой предмет (категорию), класс, учебник и тему:

6 171 185 материалов в базе

Скачать материал

Другие материалы

Оставьте свой комментарий

Авторизуйтесь, чтобы задавать вопросы.

  • Скачать материал
    • 15.02.2015 750
    • PPTX 813.5 кбайт
    • Оцените материал:
  • Настоящий материал опубликован пользователем Dudnik Oxana Antonovna. Инфоурок является информационным посредником и предоставляет пользователям возможность размещать на сайте методические материалы. Всю ответственность за опубликованные материалы, содержащиеся в них сведения, а также за соблюдение авторских прав несут пользователи, загрузившие материал на сайт

    Если Вы считаете, что материал нарушает авторские права либо по каким-то другим причинам должен быть удален с сайта, Вы можете оставить жалобу на материал.

    Удалить материал
  • Автор материала

    Dudnik Oxana Antonovna
    Dudnik Oxana Antonovna
    • На сайте: 8 лет и 2 месяца
    • Подписчики: 1
    • Всего просмотров: 24871
    • Всего материалов: 37

Ваша скидка на курсы

40%
Скидка для нового слушателя. Войдите на сайт, чтобы применить скидку к любому курсу
Курсы со скидкой