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
while(studentlist.contains(integer));你仔细看下这里有问题没??? 应该是while(integer.contains(integer)),因为你是要把integerlist作为ID,只要integerlist里没有重复的数就行了,而你判断Studentlist.contains(integer)因为这时studentlist内没有元素,所以会一直成立,因此integerlis有可能会出现相同的数
我都没完成这个呢
List<Student> sdList = new ArrayList<Student>(); List<Integer> itgList = new ArrayList<Integer>(); Random random = new Random(); Integer k; for (int i = 0; i < 3; i++) { do { k = random.nextInt(10); } while (itgList.contains(k)); itgList.add(k); } sdList.add(new Student(itgList.get(0)+"", "Tom")); sdList.add(new Student(itgList.get(1) + "", "Lindy")); sdList.add(new Student(itgList.get(2) + "", "Peo"));
Student集合中有多个属性,调用contains方法好像并不能添加随机数进去,输出sdList.size()为0.
用itgList 集合判断是否包含重复随机数。