Thứ Sáu, 22 tháng 4, 2016

Comparator interface trong java

Để cung cấp phương thức so sánh hai đối tượng với nhau, java cung cấp cho ta interface comparator. Interface này bắt ta phải cài đặt hàm compare trả lại 1 giá trị
VD: compare(A,B) = 0 <==> A = B
compare(A,B) < 0 <==> A < B
compare(A,B) > 0 <==> A > B.
Ta sẽ hiểu rõ hơn với code bằng java sau

// Java program to demonstrate working of Comparator
// interface
import java.util.*;
import java.lang.*;
import java.io.*;

// A class to represent a student.
class Student
{
    int rollno;
    String name, address;

    // Constructor
    public Student(int rollno, String name,
                               String address)
    {
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }

    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name +
                           " " + this.address;
    }
}

class Sortbyroll implements Comparator<Student>
{
    public int compare(Student a, Student b)
    {
        // return < 0 if we want a to come before b
        // in soreted order,
        // > 0 if a comes after b,
        // = 0 if a == b
        return a.rollno - b.rollno;
    }
}

class Sortbyname implements Comparator<Student>
{
    public int compare(Student a, Student b)
    {
        // <0 if we want a to come before b in sorted
        // order,
        // >0 if a comes after b,
        // =0 if a==b
        return a.name.compareTo(b.name);
    }
}

// Driver class
class Main
{
    public static void main (String[] args)
    {
        ArrayList<Student> ar = new ArrayList<Student>();
        ar.add(new Student(111, "bbbb", "london"));
        ar.add(new Student(131, "aaaa", "nyc"));
        ar.add(new Student(121, "cccc", "jaipur"));

        System.out.println("Unsorted");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));

        Collections.sort(ar, new Sortbyroll());

        System.out.println("\nSorted by rollno");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));

        Collections.sort(ar, new Sortbyname());

        System.out.println("\nSorted by name");
        for (int i=0; i<ar.size(); i++)
            System.out.println(ar.get(i));
    }
}

1 nhận xét:

  1. Caesars Hotel & Casino - Mapyro
    Find 인천광역 출장안마 the best prices on 서산 출장마사지 Harrah's 강릉 출장샵 Cherokee Casino in Murphy on Mapyro. 아산 출장마사지 View real-time driving directions, reviews 의정부 출장안마 and updates.

    Trả lờiXóa

Copyright © Dịch từ nguồn geeksforgeeks.org

Distributed By My Blogger Themes | Blogger Theme By NewBloggerThemes Up ↑