集合框架_ArrayList存储自定义对象并排序案例

网友投稿 828 2022-10-14

集合框架_ArrayList存储自定义对象并排序案例

集合框架_ArrayList存储自定义对象并排序案例

package cn.itcast_02;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;/* * Collections可以针对ArrayList存储基本包装类的元素排序,存储自定义对象可不可以排序呢? * */public class CollectionsDemo { public static void main(String[] args) { // 创建集合对象 List list = new ArrayList(); // 创建学生对象 Student s1 = new Student("张三", 25); Student s2 = new Student("李四", 22); Student s3 = new Student("王五", 30); Student s4 = new Student("李四", 22); // 添加元还给 list.add(s1); list.add(s2); list.add(s3); list.add(s4); // 排序 // 自然排序 // Collections.sort(list); // 比较器排序 // 如果同时有自然排序和比较器排序,以比较器排序为主 Collections.sort(list, new Comparator() { @Override public int compare(Student s1, Student s2) { int num = s2.getAge() - s1.getAge(); int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } }); List Newlist = new ArrayList(); for (int x = 0; x < list.size(); x++) { Student stu = list.get(x); if (!Newlist.contains(stu)) { Newlist.add(stu); } } // 遍历集合 for (Student stu : Newlist) { System.out.println(stu.getName() + "---" + stu.getAge()); } }}

package cn.itcast_02;public class Student implements Comparable { private String name; private int age; public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Student s) { int num = this.age - s.age; int num2 = num == 0 ? this.name.compareTo(s.name) : num; return num2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:KSC认证代理服务程序
下一篇:CLI应用程序的花哨logger
相关文章

 发表评论

暂时没有评论,来抢沙发吧~