You are on page 1of 20

27/09/2014

BI 10.
COLLECTIONS FRAMEWORK

Ni dung
Gii thiu chung
Cc giao din trong Collections framework
List v Iterator
Tm kim v sp xp trn List

27/09/2014

1. GII THIU CHUNG V COLLECTION

Collection l g?
Collection l mt i tng m n nhm cc i tng

khc thnh phn t v cung cp cc phng thc c bn


thm, xa, ly, duyt cc phn t
Phn t ca Collection khng c php l kiu nguyn thy

Collections Framwork thng nht cch thc s dng cc

collection, gm 3 thnh phn chnh:


Giao din
Lp trin khai
Thut ton

S dng i tng Iterator duyt qua tt c cc phn

t ca collection
c xy dng da trn k thut lp trnh tng qut
u im: tin dng, hiu nng cao
4

27/09/2014

Cc giao din v lp trin khai

Mt v d n gin
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListPostJDK15Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("alpha"); // add an element
list.add("beta");
list.add("charlie");
System.out.println(list); // [alpha, beta, charlie]

27/09/2014

Mt v d n gin(tip)
// Iterator of Strings
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String str = iter.next();
System.out.println(str);
}
for (String str : list) {
System.out.println(str);
}
}
}

2. CC GIAO DIN COLLECTION

27/09/2014

Cc giao din

Cc giao din (tip)


Giao din Iterable<E>
//Tr li mt i tng Iterator duyt qua cc phn t
Iterator<E> iterator()

Giao din Iterator<E>


// Tr v true nu cn phn t cha c duyt
boolean hasNext()
// Tr v phn t tip theo trong collection
E next()
// Xa phn t ang duyt
void remove()

10

27/09/2014

Collection<E>
// Tr v s phn t ca collection
int size()
// Xa mi phn t trong collection
void clear()
// Tr v true nu khng c phn t no trong collection
boolean isEmpty()
// Thm 1 phn t vo collection, tr v true nu thnh cng
boolean add(E element)
// Xa 1 phn t, tr v true nu thnh cng
boolean remove(Object element)
//Tr v true nu trong collection cha phn t element
boolean contains(Object element)
// Chuyn collection thnh mng
Object[] toArray()

11

List<E>, Set<E> v Queue<E>


L cc giao din k tha t giao din Collection
List<E>: lu tr cc phn t mt cch tun t, cc phn

t c th ging nhau mng c kch thc thay i


Cc lp trin khai: ArrayList, LinkedList, Vector,

Stack

Set<E>: m hnh ha tp hp trong Ton hc, khng

chp nhn c cc phn t ging nhau


Cc lp trin khai: Set, HashSet, LinkedHashSet
Cc giao din k tha: SortedSet<E> c trin khai l TreeSet

Queue<E>: Hng i FIFO


Giao din con: Deque<E>
Trin khai t giao din con: PriorityQueue, ArrayDeque v
LinkedList.
12

27/09/2014

Giao din Map<E>


T chc cc phn t thnh cp <K,V>
K: kha. Khng chp nhn kha c gi tr trng nhau
V: gi tr

Cc trin khai: HashMap, Hashtable,

LinkedHashMap
Giao din con: SortedMap<K, V>
Trin khai: TreeMap

13

3. LIST<E> V CC LP TRIN KHAI

14

27/09/2014

Cy k tha

15

Giao din List<e>


//Mt s phng thc truy cp danh sch qua ch s
void add(int index, E element) // thm
E set(int index, E element)
// thay th
E get(int index)
// ly phn t
E remove(int index)
// xa phn t
//v tr ca phn t u tin ging vi obj
int indexOf(Object obj)
//v tr ca phn t cui cng ging obj
int lastIndexOf(Object obj)
//Ly ra mt danh sch con
List<E> subList(int fromIndex, int toIndex)

16

27/09/2014

Giao din List<e>


//Mt s phng thc k tha t Collection
int size()
boolean isEmpty()
boolean add(E element)
boolean remove(Object obj)
boolean contains(Object obj)
void clear()

17

Cc lp trin khai t List<E>


ArrayList: lp trin khai tin dng nht, c s dng

thng xuyn thay th cho mng


Cc phng thc ca ArrayList l khng ng b (non-

synchronized)
Khi c nhiu lung truy cp ti ArrayList cn ng b ha cc
lung bng Collections.synchronizedList(List<E> list)

Vector: c pht trin t Java 1.0, hin t dng


Cc phng thc ca Vector l ng b (synchronized)

h tr truy cp a lung

Hiu nng chng trnh khi s dng ArrayList tt hn


Stack: k tha t Vector (s cp sau)
LinkedList: danh sch lin kt (s cp sau)
18

27/09/2014

ArrayList V d
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
/**
* The ArrayListExamples class illutrates the usage of the
ArrayList in the Colections Framework
*/
public class ArrayListExamples {
public static void main(String args[]) {
// Creating an empty array list
ArrayList<String> list = new ArrayList<String>();
// Adding items to arrayList
list.add("Item1");
list.add("Item3");
list.add(1, "Item2"); // Add Item3 to the second position
//of array list. The other elements
//are pushed backward.
list.add("Item4");
19

ArrayList V d(tip)
// Display the contents of the array list
System.out.println("The arraylist contains the
following elements: "+ list);
// Checking index of an item
int pos = list.indexOf("Item2");
System.out.println("The index of Item2 is: " + pos);
// Checking if array list is empty
boolean check = list.isEmpty();
System.out.println("Checking if the arraylist is
empty: " + check);
// Getting the size of the list
int size = list.size();
System.out.println("The size of the list is: " +
size);
20

10

27/09/2014

ArrayList V d(tip)
// Checking if an element is included to the list
boolean inList = list.contains("Item5");
System.out.println("Checking if the arraylist contains
the object Item5: " + inList);
// Getting the element in a specific position
String item = list.get(0);
System.out.println("The item is the index 0 is: " +
item);
// Retrieve elements from the arraylist
// 1st way: loop using index and size list
System.out.println("Retrieving items with loop using
index and size list");
for (int i = 0; i < list.size(); i++) {
System.out.println("Index: " + i + " - Item: " +
list.get(i));
}
21

ArrayList V d(tip)
// 2nd way:using foreach loop
System.out.println("Retrieving items using foreach
loop");
for (String str : list) {
System.out.println("Item is: " + str);
}
// 3rd way:using iterator
// hasNext(): returns true if there are more elements
// next(): returns the next element
System.out.println("Retrieving items using iterator");
for (Iterator<String> i = list.iterator();
i.hasNext();) {
System.out.println("Item is: " + i.next());
}
22

11

27/09/2014

ArrayList V d(tip)
// Replacing an element
list.set(1, "NewItem");
System.out.println("The arraylist after the
replacement is: " + list);
// Removing items
// removing the item in index 0
list.remove(0);
// removing the first occurrence of item "Item3"
list.remove("Item3");
System.out.println("The final contents of the
arraylist are: " + list);
}

23

Chuyn i List thnh mng


Object[] toArray()
<T> T[] toArray(T[] a)

// S dng mng Object[]


// S dng kiu tng qut

V d
List<String> list = new ArrayList<String>();
list.add("alpha");
list.add("beta");
list.add("charlie");
// S dng mng Object[]
Object[] strArray1 = list.toArray();
System.out.println(Arrays.toString(strArray1));
// S dng kiu tng qut. Cn truyn tham s l kiu d liu
String[] strArray2 = list.toArray(new String[0]);
strArray2[0] = "delta";
// modify the returned array
System.out.println(Arrays.toString(strArray2));
System.out.println(list);
24

12

27/09/2014

Chuyn mng thnh List


public static <T> List<T> asList(T[] a)

V d
String[] strs = {"alpha", "beta", "charlie"};
System.out.println(Arrays.toString(strs)); // [alpha, beta,
//charlie]
List<String> list = Arrays.asList(strs);
System.out.println(list); // [alpha, beta, charlie]
// Changes in array or list write thru
strs[0] += "88";
list.set(2, list.get(2) + "99");
System.out.println(Arrays.toString(strs)); // [alpha88, beta,
//charlie99]
System.out.println(list); // [alpha88, beta, charlie99]
// Initialize a list using an array
List<Integer> listInt = Arrays.asList(22, 44, 11, 33);
System.out.println(listInt); // [22, 44, 11, 33]
25

4. SP XP V TM KIM

26

13

27/09/2014

Sp xp trn Collection
Mt s lp trong Collections Framework c sp xp

sn, nh SortedSet, SortedMap


Cc lp khc cung cp sn cc phng thc sp xp,

nhng cn nh ngha cch thc so snh cc phn t


Collections.sort()
Arrays.sort()

nh ngha cch thc so snh cc phn t: 2 cch


Lp ca cc phn t phi trin khai t giao din
java.lang.Comparable<E>
Vit b so snh trin khai t giao din
java.util.Comparator<E>

27

Sp xp vi Comparable<E>
Lp trin khai nh ngha phng thc int

compareTo(E obj) tr v:
0 nu bng i tng so snh obj
Nh hn 0 nu nh hn i tng so snh
Ln hn 0 nu ln hn i tng so snh

Khi nh ngha compareTo() cn thng nht vi kt qu

tr v ca equals():
Nu compareTo() tr v 0, equals() nn tr v true

Cc lp bao v lp String u l cc lp trin khai t

Comparable

28

14

27/09/2014

Comparable V d
public class Student implements Comparable<Student>{
private String id;
private String name;
private int level;
@Override
public int compareTo(Student o) {
return this.id.compareToIgnoreCase(o.id);
}
//Declare other methods
}

29

Comparable V d
public class StudentSortDemo{
Student[] arr = new Student[50];
List<Student> list = new ArrayList<Student>();
//enter data for arr and list...
//sort arr
Arrays.sort(arr);
//sort list
Collections.sort(arr);
//Display results...
}

Lm th no sp xp theo nhiu tiu ch?


30

15

27/09/2014

Sp xp vi Comparator<E>
nh ngha b so snh trin khai t Comparator<E>,

nh ngha phng thc int compare(E o1, E o2)


tr v:
0 nu o1 == o2
Nh hn 0 nu o1<o2
Ln hn 0 nu o1>o2

Khng bt buc lp ca cc phn t phi k tha t giao

din Comparable
Tin dng hn
Mm do hn: c th vit nhiu b so snh theo cc tiu ch khc

nhau

31

Comparator V d
public class Student{
private String id;
private String name;
private int level;
//Declare methods
}

32

16

27/09/2014

Comparable V d
public class StudentSortDemo{
Student[] arr = new Student[50];
List<Student> list = new ArrayList<Student>();
public static class StudentComparator
implements Comparator<Student>{
@Override
public int compare(Student s1, Student s2){
return s1.id.compareToIgnoreCase(s2.id);
}
}
Comparator<Student> compStudent = new StudentComparator();
//sort arr
Arrays.sort(arr, compStudent);
//sort list
Collections.sort(arr, compStudent);
//Display results...
}
33

Tm kim
Tm kim tun t
Mng: duyt v so snh
Collection: boolean contains(Object o)
List:
int indexOf(Object o)
int lastIndexOf(Object o)

Tm kim nh phn: ch thc hin khi mng, collection

c sp xp. S dng cc phng thc tnh ca lp


Arrays v Collections
Tr v ch s ca phn t nu tm thy
Tr v -1 nu khng tm thy

34

17

27/09/2014

Tm kim nh phn V d
Lp ca cc phn t trin khai t Comparable<E>
Arrays.binarySearch(Object[] arr, Object key)
Arrays.binarySearch(Object[], int from, int to,
Object key)
Collections.binarySearch(List<E>, E key)
S dng b so snh trin khai t Comparator<E>
Arrays.binarySearch(E[], E key, Comparator<E> c)
Arrays.binarySearch(E[], int from, int to,
E key, Comparator<E> c)
Collections.binarySearch(List<E>, E key,
Comparator<E> c)

35

Tm kim nh phn V d
public class Student implements Comparable<Student>{
private String id;
private String name;
private int level;
@Override
public int compareTo(Student o) {
return this.id.compareToIgnoreCase(o.id);
}
//Declare other methods
}

36

18

27/09/2014

Tm kim nh phn V d(tip)


public class StudentSortDemo{
Student[] arr = new Student[50];
List<Student> list = new ArrayList<Student>();
Arrays.sort(arr);
Student student = new Student(20123456);
System.out.println(Found this student at +
Arrays.binarySearch(arr, student));
Collections.sort(arr);
System.out.println(Found this student at +
Collections.binarySearch(list, student));
}

37

Tm kim nh phn V d khc


public class Student{
private String id;
private String name;
private int level;
//Declare methods
}

38

19

27/09/2014

Tm kim nh phn V d khc


public class StudentSortDemo{
Student[] arr = new Student[50];
List<Student> list = new ArrayList<Student>();
public static class StudentComparator
implements Comparator<Student>{
@Override
public int compare(Student s1, Student s2){
return s1.id.compareToIgnoreCase(s2.id);
}
}
Comparator<Student> compStudent = new StudentComparator();
Arrays.sort(arr, compStudent);
Student student = new Student(20123456);
System.out.println(Found this student at +
Arrays.binarySearch(arr, student, compStudent));
Collections.sort(arr, compStudent);
System.out.println(Found this student at +
Arrays.binarySearch(list, student, compStudent));
}
39

20

You might also like