[Thực hành] Sắp xếp với Comparable và Comparator

NỘI DUNG BÀI VIẾT

Mục đích

Biết cách sử dụng Comparable và Comparator

Mô tả

Tạo một lớp Student chứa thông tin về tên, tuổi, địa chỉ.

Thực hiện sắp xếp các đối tượng student theo tên và tuổi

Hướng dẫn nộp bài:

  • Up mã nguồn lên github
  • Paste link github vào phần nộp bài

Hướng dẫn

Bước 1: Tạo lớp lớp Student thực thi giao diện Comparable

public class Student implements Comparable <Student> {

private String name;
private Integer age;
private String address;

public Student(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}

@Override
public int compareTo(Student student) {
return this.getName().compareTo(student.getName());
}
}

Bước 2: Tạo lớp AgeComparator thực thi giao diện Comparator

public class AgeComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge() > o2.getAge()){
return 1;
}else if(o1.getAge() == o2.getAge()){
return 0;
}else{
return -1;
}
}
}

Bước 3: Tạo hàm Main để kiểm tra kết quả so sánh

 public static void main(String[] args) {
Student student = new Student("Kien", 30, "HT");
Student student1 = new Student("Nam", 26, "HN");
Student student2 = new Student("Anh", 38, "HT" );
Student student3 = new Student("Tung", 38, "HT" );

List<Student> lists = new ArrayList<Student>();
lists.add(student);
lists.add(student1);
lists.add(student2);
lists.add(student3);
Collections.sort(lists);
for(Student st : lists){
System.out.println(st.toString());
}

AgeComparator ageComparator = new AgeComparator();
Collections.sort(lists,ageComparator);
System.out.println("So sanh theo tuoi:");
for(Student st : lists){
System.out.println(st.toString());
}
}

Bài viết liên quan

Trả lời

Email của bạn sẽ không được hiển thị công khai.

Tài liệu + Khóa học lập trình FREE
Tài liệu + Khóa học lập trình FREE

DMCA.com Protection Status