完善不重复的ID,但是我发现按照老师说的写,还是可能出现重复,这是为什么呢
public void testArray4(){ List<Student> studentlist=new ArrayList<Student>(); List<Integer> integerlist=new ArrayList<Integer>(); Random random=new Random(); Integer integer; for(int i=0;i<3;i++){ do{ integer=random.nextInt(10); }while(studentlist.contains(integer)); integerlist.add(integer); } studentlist.add(new Student(integerlist.get(0)+"","chen")); studentlist.add(new Student(integerlist.get(1)+"","wang")); studentlist.add(new Student(integerlist.get(2)+"","zhang")); // studentlist.add(new Student(1000+"","li")); System.out.println("-------排序前-----"); for (Student student : studentlist) { System.out.println("元素:"+student.id+":"+student.name); } Collections.sort(studentlist); System.out.println("---------排序后---------"); for (Student student : studentlist) { System.out.println("元素:"+student.id+":"+student.name); } Collections.sort(studentlist, new Studentlist()); System.out.println("---------按照姓名排序后---------"); for (Student student : studentlist) { System.out.println("元素:"+student.id+":"+student.name); } }
其中一个运行结果:
-------排序前-----
元素:8:chen
元素:4:wang
元素:4:zhang
---------排序后---------
元素:4:wang
元素:4:zhang
元素:8:chen
---------按照姓名排序后---------
元素:8:chen
元素:4:wang
元素:4:zhang