| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2146 人关注过本帖
标题:关于set方法的使用和Comparator接口的使用
取消只看楼主 加入收藏
xbanyue
Rank: 1
等 级:新手上路
帖 子:15
专家分:0
注 册:2018-4-26
结帖率:0
收藏
已结贴  问题点数:20 回复次数:0 
关于set方法的使用和Comparator接口的使用
public class Person implements Comparable{   
    int id;
    int age;
    String name;
    public Person(int id, int age, String name) {
        super();
        this.id = id;
        this.age = age;
        this.name = name;
    }
    public String toString() {
        return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
    }
    public int compareTo(Object o) {
        Person p;
        if(o instanceof Person) {
            p=(Person)o;
        }else {
            return -1;   
        }
        int diff=this.id-p.id;
        if(diff!=0) {
            diff=diff/Math.abs(diff);
        }
        return diff;
    }   
}
//////////上面的是person类/////////
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Demo  {
    public static void main(String[] args) {
        Set set=new TreeSet();
        Person p1=new Person(1,18,"小明");
        Person p2=new Person(3,17,"小明");
        Person p3=new Person(2,15,"小李");
        set.add(p1);
        set.add(p2);
        set.add(p3);
        System.out.println(set.size());
        Iterator it=set.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
//////下面的是dome类(包含主程序入口)//////////
下面是打印结果
3
Person [id=1, age=18, name=小明]
Person [id=2, age=15, name=小李]
Person [id=3, age=17, name=小明]
我想问的是主程序中是如果调用了person类中的方法啊,定义了person对象,但并没有调用方法,整个程序给我感觉一脸懵的感觉。
搜索更多相关主题的帖子: set Person int age name 
2018-06-13 11:50
快速回复:关于set方法的使用和Comparator接口的使用
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012140 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved