1. Trang chủ
  2. » Công Nghệ Thông Tin

Bài giảng Lập trình hướng đối tượng: Chương 5 - Châu Thị Bảo Hà

58 6 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Chương 5 - Tập Hợp Trên Java
Trường học Trường Đại Học Công Nghệ Thông Tin
Chuyên ngành Lập trình hướng đối tượng
Thể loại Bài giảng
Định dạng
Số trang 58
Dung lượng 1,43 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Bài giảng Lập trình hướng đối tượng - Chương 5 trình bày những nội dung liên quan đến tập hợp trên java. Sau khi học xong chương này người học có thể: Phân biệt được tập hợp và mảng, phân biệt được các đặc trưng của các Collection interface, biết cách chọn loại tập hợp thích hợp để giải quyết bài toán. Mời các bạn tham khảo.

Trang 1

Chương 5 TẬP HỢP TRÊN JAVA

Trang 2

Mục tiêu

• Phân biệt tập hợp và mảng

• Phân biệt các đặc trưng của các Collection interface

• Chọn loại tập hợp thích hợp để giải quyết bài toán

Trang 4

5.1 Khái niệm về tập hợp

• Tập hợp là đối tượng có khả năng chứa các đối tượng khác

• Các đối tượng của tập hợp có thể thuộc nhiều loại dữ liệu khác nhau

• Các thao tác thông thường trên tập hợp

o Thêm/Xoá đối tượng vào/ra tập hợp

o Kiểm tra một đối tượng có tồn tai trong tập hợp hay không

o Lấy một đối tượng từ tập hợp

o Duyệt các đối tượng trong tập hợp

o Xoá toàn bộ tập hợp

o …

Trang 5

5.1 Khái niệm về tập hợp Collections Framework

• Collections Framework (từ Java 1.2)

o Là một kiến trúc hợp nhất để biểu diễn và thao tác trên các loại tập hợp

o Giúp cho việc xử lý tập hợp độc lập với biểu diễn chi tiết bên trong của chúng

• Một số lợi ích của Collections Framework

o Giảm thời gian lập trình

o Tăng cường hiệu năng chương trình

o Dễ mở rộng các collection mới

o Sử dụng lại mã chương trình

Trang 6

5.1 Khái niệm về tập hợp Collections Framework

• Collections Framework bao gồm:

o Interfaces : Là các interface thể hiện tính chất của các kiểu collection khác nhau như List, Set, Map

o Implementations : Là các lớp collection có sẵn được cài đặt các collection interfaces như LinkedList, HashSet

o Algorithms : Là các phương thức tĩnh để xử lý trên collection, ví dụ: sắp xếp danh sách, tìm phần tử lớn nhất

Trang 7

5.1 Khái niệm về tập hợp Collection và Map interface

Interface gốc chứa các phương thức chung cho tất cả các loại collections

Theo cơ chế FIFO và hàng đợi

ưu tiên Lưu trữ theo thứ tự thêm vào Truy xuất theo chỉ mục (index)

Có thể trùng nhau

Lưu trữ không theo thứ

tự thêm vào, không cho

phép trùng

Lưu trữ các phần tử theo

thứ tự tăng

Lưu trữ các ánh xạ từ khóa đến giá trị

Các khóa được sắp thứ tự

Trang 8

+ get (int):E + indexOf (Object):int

+contains(Object):boolean +size():int

+iterator():Iterator<E> etc…

<<interface>>

Set<E> +add(E):boolean +remove(Object):boolean

+contains(Object):boolean +size():int

+iterator():Iterator<E>

+ first ():E + last ():E etc…

<<interface>>

SortedSet<E>

Trang 9

5.1 Khái niệm về tập hợp

Các phương thức của Collection interface

Trang 11

5.1 Khái niệm về tập hợp

Duyệt collection

• Các phương thức của Iterator:

o boolean hasNext (): trả về true nếu còn phần tử chưa duyệt

=

Trang 12

5.1 Khái niệm về tập hợp Comparable<T> interface

• Comparable<T> interface có 1 phương thức: int compareTo(T)

o Trả về 0 nếu this = other

o Trả về một số dương nếu this > other

o Trả về một số âm nếu this < other

public class Student implements Comparable <Student> {

.

public int compareTo ( Student other ) {

if( this.gpa == other.gpa ) {

Cách viết khác trong hàm compareTo:

return this.gpa – other.gpa;

Trang 13

5.1 Khái niệm về tập hợp Comparable<T> interface

List<Student> listStudent = new ArrayList <Student>();

public static <T extends Comparable<? super T>> void sort(List<T> list)

What’s the output?

[Laura-2, Fred-3, Steve-3, Sam-4]

Wildcard (later)

Trang 14

5.1 Khái niệm về tập hợp Comparator<T> interface

• Sử dụng trong trường hợp không thể Comparable, hoặc muốn định nghĩa thêm các thứ tự khác

public class StudentNameComparator implements Comparator <Student> {

public int compare (Student o1, Student o2) {

return o1.getName().compareToIgnoreCase(o2.getName());

}

}

Trang 15

5.1 Khái niệm về tập hợp Comparator<T> interface

What’s the output?

[Fred-3, Laura-2, Sam-4, Steve-3]

Trang 16

5.1 Khái niệm về tập hợp

List interface

• Kế thừa Collection, Iterable interface

• Lưu trữ theo thứ tự thêm vào

public int compare(User o1, User o2) {

return o2.getOld() - o1.getOld();

}

});

Trang 17

5.1 Khái niệm về tập hợp Set and SortedSet interface

• Set interface

o Hiện thực Collection, Iterable interface

o Các phần tử lưu trong Set không được trùng và không quan tâm thứ tự thêm vào

o Không có phương thức riêng ngoài các phương thức kế thừa từ

Collection

• SortedSet interface

o Hiện thực Set, Collection, Iterable interface

o Hỗ trợ thao tác trên tập hợp các phần tử có thể so sánh được

• Các Object đưa vào SortedSet phải có khả năng so sánh được, tức là phải implements Comparable interface

Trang 20

5.1 Khái niệm về tập hợp

Map interface

• Hai phương thức truy cập:

o V put (K key, V value) // Thêm cặp key-value vào map

o V get (Object key) // Trả về value tương ứng với key cho trước

Trang 22

5.2 So sánh tập hợp và mảng

Chứa 1 loại đối tượng/dữ liệu nhất

Trang 26

5.3 Các lớp tập hợp trong Java

Lớp ArrayList

• Thực thi List interface

• Phù hợp khi cần truy xuất ngẫu nhiên các phần tử trong tập hợp

• Các hàm khởi tạo:

Trang 27

5.3 Các lớp tập hợp trong Java

Lớp ArrayList

• Ví dụ:

Output

Trang 29

5.3 Các lớp tập hợp trong Java

Lớp LinkedList

• Thực thi List và Queue interface

• Các phần tử được lưu trữ dạng một danh sách liên kết

• Các phương thức

Trang 30

5.3 Các lớp tập hợp trong Java

Lớp HashSet

• Thực thi Set interface

• Sử dụng Hash Table để lưu dữ liệu

3

Trang 31

5.3 Các lớp tập hợp trong Java

Lớp LinkedHashSet

• Kết hợp giữa HashSet và LinkedList

• Sử dụng một List để duy trì thứ tự của các phần tử như khi chúng được thêm vào

Trang 32

5.3 Các lớp tập hợp trong Java

Lớp LinkedHashSet

• Ví dụ:

Trang 33

5.3 Các lớp tập hợp trong Java

Lớp TreeSet

• Thực thi SortedSet interface

• Lưu giữ liệu theo cấu trúc “cây”

• Các phần tử được lưu trữ theo thứ tự tăng dần

• Có thể quy định thứ tự bằng:

o Comparable (theo thứ tự tự nhiên)

o Comparator

Trang 34

What’s the output?

Ants; Bats; Crabs

Trang 35

public class Student implements Comparable <Student> {

private String name;

private int gpa;

Trang 36

5.3 Các lớp tập hợp trong Java

Lớp TreeSet

• Ví dụ: Truyền Comparator vào constructor của TreeSet

Set studentSet = new TreeSet<Student>(new StudentNameComparator());

public class StudentNameComparator implements Comparator <Student> {

public int compare(Student o1, Student o2) {

Student

- name

- gpa

Trang 37

5.3 Các lớp tập hợp trong Java

Lớp HashMap

• Thực thi Map interface

• Ví dụ:

Trang 38

5.3 Các lớp tập hợp trong Java

Lớp TreeMap

• Lưu trữ các phần tử theo cấu trúc cây

• Các phần tử sắp xếp dựa trên giá trị của khóa

• Các hàm:

Trang 39

5.3 Các lớp tập hợp trong Java

Lớp TreeMap

• Ví dụ:

Trang 42

5.3 Các lớp tập hợp trong Java

Lớp PriorityQueue

Trang 44

5.3 Các lớp tập hợp trong Java

Lớp Arrays

Output

• Ví dụ:

Trang 45

5.3 Các lớp tập hợp trong Java Các lớp bao (wrapper classes)

• Collection chỉ làm việc trên các Object Những kiểu dữ liệu cơ bản như: byte, short, int, long, double, float, char, boolean không thể đưa được trực tiếp vào Collection mà phải thông qua các lớp bao

• Các lớp bao: Byte, Short, Integer, Long, Double, Float, Char, Boolean

• Ví dụ:

Integer intObject = new Integer(9);

int value = intObject.intValue();

Trang 46

5.3 Các lớp tập hợp trong Java Lựa chọn sử dụng Collection

1) Determine how you access values

o Values are accessed by an integer position Use an ArrayList

• Go to Step 2, then stop

o Values are accessed by a key that is not a part of the object

• Use a Map

o It doesn’t matter Values are always accessed “in bulk”, by traversing the collection and doing something with each value

2) Determine the element types or key/value types

o For a List or Set, a single type

o For a Map, the key type and the value type

Trang 47

5.3 Các lớp tập hợp trong Java Lựa chọn sử dụng Collection

3) Determine whether element or key order matters

o Elements or keys must be sorted

• Use a TreeSet or TreeMap Go to Step 6

o Elements must be in the same order in which they were inserted

• Your choice is now narrowed down to a LinkedList or an ArrayList

o It doesn’t matter

• If you chose a Map in Step 1, use a HashMap and go to Step 5

Trang 48

5.3 Các lớp tập hợp trong Java Lựa chọn sử dụng Collection

• 4) For a collection, determine which operations must be fast

o Finding elements must be fast

• Use a HashSet and go to Step 5

o Adding and removing elements at the beginning or the middle must be fast

• Use a LinkedList

o You only insert at the end, or you collect so few elements that you aren’t concerned about speed

• Use an ArrayList

Trang 49

5.3 Các lớp tập hợp trong Java Lựa chọn sử dụng Collection

5) For HashSet and Map, decide if you need to implement the equals and hashCode methods

o If your elements do not support them, you must implement them yourself

6) If you use a Tree, decide whether to supply a comparator

o If your element class does not provide it, implement the Comparable

interface for your element class

Trang 50

5.4 Ứng dụng của tập hợp trong lập trình

Bài tập

1 Cài đặt các xử lý Exception cần thiết cho các phương thức trong

LinkedList, Stack, Queue, Tree.

2 Viết chương trình cho phép nhập một xâu ký tự từ bàn phím, sau đó hiển

thị xâu này theo thứ tự ngược lại (dùng Stack).

3 Viết chương trình cho phép nhập một danh sách sinh viên sau đó sắp xếp

danh sách theo thứ tự tăng dần (dùng ArrayList và Collections.sort()).

4 Viết chương trình hỗ trợ tra cứu từ điển đơn giản Chương trình lưu các từ

và nghĩa của từ trong một Collection hoặc một Map.

5 Mở rộng bài tập trên bằng cách dùng file để lưu trữ các từ.

6 Giải các bài toán ứng dụng trong môn Cấu trúc dữ liệu bằng cách sử dụng

Collections Framework.

Trang 51

Special Topic: Hash Functions

• Hashing can be used to find elements in a set data structure quickly, without making a linear search through all elements

• A hashCode method computes and returns an integer value: the hash code

o Should be likely to yield different hash codes

o Because hashing is so important, the Object class has a hashCode

method that computes the hash code of any object x.

int h = x.hashCode();

Trang 52

Computing Hash Codes

• To put objects of a given class into a HashSet or use the objects as keys in a HashMap, the class should override the default hashCode method

• A good hashCode method should work such that different objects are likely to have different hash codes

o It should also be efficient

o A simple example for a String might be:

Trang 53

Computing Hash Codes

• But Strings that are permutations of another (such as "eat" and "tea") would all have the same hash code

• Better:

o From the Java Library!

final int HASH_MULTIPLIER = 31;

Trang 54

Sample Strings and HashCodes

• The String class implements a good example of a hashCode method

• It is possible for two or more distinct objects to have the same hash code: This is called a collision

o A hashCode function should minimizes collisions

Trang 55

Computing Object Hash Codes

• You should have a good hashCode method for your own objects to store them efficiently

• Override hashCode methods in your own classes by combining the hash codes for the instance variables

• Then combine the hash codes using a prime-number hash multiplier:

public int hashCode() {

int h1 = name hashCode ();

int h2 = new Double(area) hashCode ();

Trang 56

hashCode and equals methods

• hashCode methods should be compatible with equals methods

o If two objects are equal, their hashCodes should match

o a hashCode method should use all instance variables

o The hashCode method of the Object class uses the memory location of the object, not the contents

Trang 57

hashCode and equals methods

• Do not mix Object class hashCode or equals methods with your own:

o Use an existing class such as String Its hashCode and equals methods have already been implemented to work correctly.

o Implement both hashCode and equals

• Derive the hash code from the instance variables that the equals method compares, so that equal objects have the same hash code

o Implement neither hashCode nor equals Then only identical objects are considered to be equal

Ngày đăng: 21/05/2021, 12:48

🧩 Sản phẩm bạn có thể quan tâm