都是已存在
2022-02-23 20:07
package com.imooc.collection; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class CollectionsTest { public List<String> randomList(){ List<String> strList=new ArrayList<String>();; String str; Random random=new Random(); for(int i=0;i<3;i++){ do{str=random.nextInt(999)+1+""; }while(strList.contains(str)); strList.add(str); } return strList; } public void testSort3(){ List<Student> studentList=new ArrayList<Student>(); List<String> strList=randomList(); studentList.add(new Student(strList.get(0),"Mike")); studentList.add(new Student(strList.get(1),"Angela")); studentList.add(new Student(strList.get(2),"Lucy")); System.out.println("------------排序前------------"); for (Student student:studentList) { System.out.println("学生:"+student.getStudent_id()+":"+student.getStudent_name()); } Collections.sort(studentList); System.out.println("------------排序后------------"); for (Student student:studentList) { System.out.println("学生:"+student.getStudent_id()+":"+student.getStudent_name()); } System.out.println("------------按照姓名排序前------------"); for (Student student:studentList) { System.out.println("学生:"+student.getStudent_id()+":"+student.getStudent_name()); } Collections.sort(studentList,new StudentComparator()); System.out.println("------------按照姓名排序后------------"); for (Student student:studentList) { System.out.println("学生:"+student.getStudent_id()+":"+student.getStudent_name()); } } public static void main(String[] args) { CollectionsTest collectionsTest=new CollectionsTest(); collectionsTest.testSort3(); } }
/* Student类 */ package com.imooc.collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; public class Student implements Comparable<Student> { private String student_id; private String student_name; public Set<Course> student_course; public String getStudent_id(){ return this.student_id; } public void setStudent_id(String student_id){ this.student_id=student_id; } public String getStudent_name() { return this.student_name; } public void setStudent_name(String student_name) { this.student_name = student_name; } public Student(){ } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(student_name, student.student_name); } @Override public int hashCode() { return Objects.hash(student_name); } public Student(String id, String name){ this.student_id=id; this.student_name=name; this.student_course=new HashSet<Course>(); } @Override public int compareTo(Student o) { return this.student_id.compareTo(o.student_id); } }
你这个写得有些复杂了吧,用时间对象可以不?
Java入门第三季
409792 学习 · 4340 问题
相似问题