Java Comparable 和 Comparator 比较_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java Comparable 和 Comparator 比较

Java Comparable 和 Comparator 比较

 2015/4/1 6:20:03  TRAMP_ZZY  程序员俱乐部  我要评论(0)
  • 摘要:JavaComparable和Comparator比较1.代码实现packageorg.anicloud.colletion;importjava.util.Arrays;importjava.util.Comparator;/***Createdbyzhaoyuon15-4-1.*/classUserimplementsComparable<User>{privateStringid;privateintage;User(Stringid,intage){this.id=id
  • 标签:Java

Java Comparable 和 Comparator 比较

1. 代码实现

class="java">package org.anicloud.colletion;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by zhaoyu on 15-4-1.
 */

class User implements Comparable<User> {

    private String id;
    private int age;

    User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public int compareTo(User o) {
        return this.age - o.age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}

public class SampleCompatator implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        return -(o1.length() - o2.length());
    }

    public static void main(String[] args) {
        SampleCompatator sampleCompatator = new SampleCompatator();

        String[] strs = {"zhao", "yu", "zhang"};
        System.out.println(Arrays.toString(strs));
        Arrays.sort(strs, sampleCompatator);
        System.out.println(Arrays.toString(strs));

        User[] users = new User[]{new User("zhang", 23), new User("zhao", 21), new User("yu", 13)};
        System.out.println(Arrays.toString(users));
        Arrays.sort(users);
        System.out.println(Arrays.toString(users));
    }
}

?

2 比较说明

? ** ?Comparable 接口是类在设计的时直接实现的, 该类就具有比较功能.

? ** ?Comparator 接口是比较实现的算法实现,在不改动现有代码的时,另一种实现比较的方法.

上一篇: WPF学习笔记(XAML) 下一篇: 没有下一篇了!
发表评论
用户名: 匿名