集合中存储时的对象重写比较方法
来源:互联网 发布:一度教育java 编辑:程序博客网 时间:2024/06/07 13:30
当往集合里存储对象时,往Set里
import java.util.*;class Student implements Comparable{ String name ; int age ; Student(String name,int age){this.name = name;this.age = age;} public int compareTo(Object obj){ Student st = (Student) obj; int num = this.age - st.age; return num==0?this.name.compareTo(st.name):num; } public String toString(){ return name+" "+age; }}class practice1 { public static void main(String[] args) { //String str = "oeiproitwoeuraecdefgabcdefg"; TreeSet ts = new TreeSet(); ts.add(new Student("liwu",32)); ts.add(new Student("wangwu",43)); ts.add(new Student("liwu",32)); sop(ts); } public static void sop(Object obj){ System.out.println(obj); }}
还可以实现Comparactor接口,在TreeSet的构造方法中传递进去这个比较类的对象class ComByName implements Comparator{ public int compare(Object obj1,Object obj2) { if(!(obj1 instanceof Student)) throw new ClassCastException("类型转换异常"); if(!(obj2 instanceof Student)) throw new ClassCastException("类型转换异常"); Student stu1 = (Student)obj1; Student stu2 = (Student)obj2; int num = stu1.getName().compareTo(stu2.getName()); return num==0?stu1.getAge()-stu2.getAge():num; }}
0 0
- 集合中存储时的对象重写比较方法
- JAVA中自定义对象比较时重写equals()方法的同时要重写hashcode()方法
- 重写对象的hashCode()方法来对无序集合排序
- 对象的比较,排序,重写equals(),compareTo(),hashCode()方法
- 重写equals()和hashCode()方法,用于比较对象的内容
- 当request.setAtrrbute("存储对象","对象")存储是对象的时候,并且对象中有方法是集合,可以直接到网页中调用方法么?
- JAVA中自定义对象比较时重写equals…
- 黑马程序员一在hashSet集合中比较对象需要覆盖的两个方法hashCode(),equlas()
- java 集合 TreeMap 键是对象,TreeMap中要重写compareTo方法
- 为什么要重写java中对象的equals方法和hashCode方法以及如何重写
- 面向对象 子类中 < 重载 重写 >父类的方法
- 方法重写与方法重载的比较
- 筛选list集合中是否存在要比较的对象
- 用java比较两个集合对象中不一样的元素。
- 比较两个对象的内容是否相等 重写object 的equals方法
- 黑马程序员 集合里的对象所属类要按需求重写equals方法
- 重写Java Object对象的hashCode和equals方法实现集合元素按内容判重
- 关于C#类中重写ToString方法和PHP类中__tostring()方法的比较
- 七层OSI和四层网络模型
- 杂七杂八的概念
- POJ 1442 Black Box 优先队列 求前a[k]个数中第k大的数
- VS2013未能正确加载的问题
- 7.grep和正则
- 集合中存储时的对象重写比较方法
- JSP——过滤器篇
- 物理?数学题
- Catch That Cow
- Unity3d的GameObject.Find()的一些使用心得体会
- 中国剩余定理解说与整理
- 小鑫去爬山
- C#中Dispose和Close的区别 今天面试遇到的
- 使用JSP+Servlet实现图片验证码