Курс повышения квалификации
Курс повышения квалификации
Курс повышения квалификации
Видеолекция
1 слайд
Java Collections Framework (JCF) in Java
Tutorial for students of universities
Author: Oxana Dudnik
2 слайд
3 слайд
Hierarchy of Collection Framework
4 слайд
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.
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.
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.
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
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());
}
}
}
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);
}
}
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.
12 слайд
Java HashSet class
uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
contains unique elements only.
13 слайд
Difference between List and Set:
List can contain duplicate elements whereas Set contains unique elements only.
14 слайд
15 слайд
Java LinkedHashSet class:
contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
maintains insertion order.
16 слайд
17 слайд
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.
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.
20 слайд
What is difference between HashSet and HashMap?
HashSet contains only values whereas HashMap contains entry(key and value).
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.
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());
}
}
}
23 слайд
Difference between HashMap and Hashtable
24 слайд
25 слайд
Static Methods on Collections
•
Search and sort:
binarySearch()
,
sort()
Reorganization:
reverse()
,
shuffle()
Wrappings:
unModifiableCollection
,
synchonizedCollection
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 слайд
28 слайд
Comparable interface
Syntax:
public int compareTo(Object obj): is used to compare the current object with the specified object.
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;
}
30 слайд
Comparator interface
Syntax of compare method
public int compare(Object obj1,Object obj2): compares the first object with second object.
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());
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 материалов в базе
Настоящий материал опубликован пользователем Dudnik Oxana Antonovna. Инфоурок является информационным посредником и предоставляет пользователям возможность размещать на сайте методические материалы. Всю ответственность за опубликованные материалы, содержащиеся в них сведения, а также за соблюдение авторских прав несут пользователи, загрузившие материал на сайт
Если Вы считаете, что материал нарушает авторские права либо по каким-то другим причинам должен быть удален с сайта, Вы можете оставить жалобу на материал.
Удалить материалВаша скидка на курсы
40%Защита диссертации и оформление аттестационных дел
Экология: основные понятия
Игровые пособия в обучении: Палочки Кюизенера
Оставьте свой комментарий
Авторизуйтесь, чтобы задавать вопросы.