So sánh 2 tiêu chí comparator trong java năm 2024

*Lưu ý: vì post này được viết dựa trên kiến thức cá nhân nên có thể có sai sót, rất mong những ý kiến, đóng góp từ mọi người. .

1. Lời dạo đầu

Chắc các bạn cũng đã biết API Collections rồi [chưa biết cũng chả sao]. Đây là class giúp lập trình viên thao tác đủ thứ: sort phần tử, sắp xếp random phần tử, cho biết số lần xuất hiện của 1 phần tử,…với các collection: ArrayList, Vector, LinkedList,…Hôm nay mình chỉ nói đến chức năng sort của Collections.

Để mở đầu câu chuyện, xin mọi người thưởng thức source code dùng Collections để sort ArrayList có các phần tử kiểu String:

import java.util.ArrayList; import java.util.Collections; / *

  • @author Huynh Tinh */ public class TestComparasion {
    public static void main[String[] args] {
        // TODO code application logic here
        // tạo 3 mảng và add vào ArrayList rồi sort
        String hello = "hello";
        String tynk = "tynk";
        String java = "java";
        ArrayList array = new ArrayList[];
        array.add[tynk];
        array.add[java];
        Collections.sort[array];
        System.out.println[array];
    }
    
    }

Output: [hello, java, tynk]

Lưu ý: Collections không làm việc với các mảng thông thường như int[], float[]. String[],…

Vậy còn Class mà mình tự tạo thì sao ??

Đầu tiên cứ tạo ra môt class đã rồi cứ sort xem sao:

import java.util.ArrayList; import java.util.Collections; // tao class Student public class Student {

 String name;
 int age;
 int grade;
 public Student[String name, int age, int grade] {
     this.name = name;
     this.age = age;
     this.grade = grade;
 }
 public String getName[] {
     return name;
 }
 public void setName[String name] {
     this.name = name;
 }
 public int getAge[] {
     return age;
 }
 public void setAge[int age] {
     this.age = age;
 } 
 public int getGrade[] {
     return grade;
 } 
 public void setGrade[int grade] {
     this.grade = grade;
 }
// test sort Student
 public static void main[String[] args] {
     Student tynk = new Student["tynk", 19, 12];
     Student java = new Student["java", 10, 5];
     ArrayList arrayList = new ArrayList[];
     students.add[tynk];
     students.add[java];
     Collections.sort[arrayList];
     System.out.println[arrayList];
 }
}

Output: Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – Erroneous sym type: java.util.Collections.sort

Có gì hot ??? Tại sao ta có thể sort kiểu phần tử kiểu String được nhưng Student thì không ? Hay có sự khác biệt gì giữa String vs Student ?? Chúng ta hãy xem cấu trúc phương thức của sort của Collection:

static Comparable

Chủ Đề