前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中Comparable的例子和用法

java中Comparable的例子和用法

作者头像
马克java社区
修改2021-04-30 10:12:32
4930
修改2021-04-30 10:12:32
举报
文章被收录于专栏:java大数据

3.5 Comparable的用法  

马克-to-win:前面讲过进入TreeSet的每个元素是都排了序的,如果被添加的元素是我们自己定义的,就需要告诉TreeSet排序的规则,这个规则就要在Comparable中定义。在下面的例子中, 当我们要往TreeSet中添加我们自己定义的类Worker对象时,就在compareTo中定义排序规则。

例:3.5.1 

/*why in the past never implements Comparable? becasue Integer claas and

String class both implements this Comparable.

java.lang.Object

java.lang.String

All Implemented Interfaces:

CharSequence, Comparable, Serializable

 */

import java.util.*;

//Comparable接口在java.lang包中定义

//定义的方法:

//int compareTo(Object o);

//实现该接口就可以实现按用户定义的自然顺序排列对象。

/*you must implements Comparable,otherwise, when you add the second element into

 the treeset, it will report error, because it will search for Comparable

 interface. */

class Worker implements Comparable {

    int workNum;

    String name;

    int money;

    public Worker(int workNum, String name, int money) {

        this.workNum = workNum;

        this.name = name;

        this.money = money;

    }

    // 按工资排序

    /*

     * public int compareTo(Object o) Returns: a negative integer, zero, or a

     * positive integer as this object is less than, equal to, or greater than

     * the specified object. it looks like that the one that is in front is

     * small. what if two keys are the same? only print out one item.

     */

    public int compareTo(Object o) {

        Worker e = (Worker) o;

        return money - e.money;//到底谁减谁,讲师如想搞清楚,请听配套视频里的仔细分析。

        // return workNum - e.workNum;

    }

}

更多请见:https://blog.csdn.net/qq_43650923/article/details/100831985

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档