public class CollectionSort { public void sort3(){ List<Student> studentList = new ArrayList<Student>(); List<Integer> i = new ArrayList<Integer>(); Random r = new Random(); int n; for(int j=0;j<3;j++){ do{ n = r.nextInt(1000); }while(i.contains(n)); i.add(n); } studentList.add(new Student(i.get(0).toString(),"小明")); studentList.add(new Student(i.get(1).toString(),"小红")); studentList.add(new Student(i.get(2).toString(),"小刚")); 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); } } public static void main(String[] args) { CollectionSort cs = new CollectionSort(); cs.sort3(); } } 多多指教!
好想法,比我想的要简单
学到了,你那种方法也不错
public void testSort3(){ List<Student> studentList =new ArrayList<Student>(); Random random =new Random(); Integer a = 10001; Integer[] readNums = new Integer[3]; for(int i=0;i<3;i++){ do{k=random.nextInt(1000); }while( a==k); a=k; readNums[i]=k; } studentList.add(new Student(readNums[0]+"","小明")); studentList.add(new Student(readNums[1]+"","小红")); studentList.add(new Student(readNums[2]+"","小兰")); System.out.println("--------排列前-----------"); for (Student student : studentList) { System.out.println("学生:"+student.name); } Collections.sort(studentList); }
public void testSort3(){
List<Student> studentList =new ArrayList<Student>();
Random random =new Random();
Integer a = 10001;
Integer[] readNums = new Integer[3];
for(int i=0;i<3;i++){
do{k=random.nextInt(1000);
}while( a==k);
a=k;
readNums[i]=k;
}
studentList.add(new Student(readNums[0]+"","小明"));
studentList.add(new Student(readNums[1]+"","小红"));
studentList.add(new Student(readNums[2]+"","小兰"));
System.out.println("--------排列前-----------");
for (Student student : studentList) {
System.out.println("学生:"+student.name);
}
Collections.sort(studentList);
}
不知有没有更简单的方法来实现
学习了。感觉对于对象引用名称的定义要更详细点。一个i,一个n感觉不太好。