// 三个不重复的整数
while (i == j)
{
j = random.nextInt(1000);
}
while (i == k || k == j)
{
k = random.nextInt(1000);
}
studentList.add(new Student(i + "", "Mike"));
studentList.add(new Student(j + "", "Angela"));
studentList.add(new Student(k + "", "Lucy"));
我感觉这个实现太长了,谁有更简洁的方法来实现
如图,加油
/** * 3.对其他类型泛型的List进行排序,以Student为例。 */ public void testSort3() { List<Student> studentList = new ArrayList<Student>(); Random random = new Random(); int f = random.nextInt(1000); studentList.add(new Student(f + "", "Mike")); do f = random.nextInt(1000); while (studentList.contains(f)); studentList.add(new Student(f + "", "Zom")); do f = random.nextInt(1000); while (studentList.contains(f)); studentList.add(new Student(f + "", "Jason")); System.out.println("---------HOME----------"); for (Student student : studentList) { System.out.println("学生:" + student.getId() + "," + student.getName()); } System.out.println("---------END----------"); Collections.sort(studentList); for (Student student : studentList) { System.out.println("学生:" + student.getId() + "," + student.getName()); } } 不知道我这个算不算简单, 使用了ArrayList的contains方法判断元素是否重复, 元素重复返回true。
public void testSort3(){
List<Integer> integerList = new ArrayList<Integer>();
List<Student> studentList = new ArrayList<Student>();
Random random=new Random();
Integer k;
for(int i=0;i<3;i++){
do{ k=random.nextInt(100);
}while(integerList.contains(k));
integerList.add(k);
}
studentList.add(new Student(integerList.get(0)+"","Mike"));
studentList.add(new Student(integerList.get(1)+"","Angela"));
studentList.add(new Student(integerList.get(2)+"","Lucy"));
脑子笨,把testSort1合并进来用了
int i; int j; int k; do { i = random.nextInt(10); j = random.nextInt(10); k = random.nextInt(10); }while (i==j||i==k||j==k);
不知道我的这个是不是简单易懂呢
public void test(){ Set<Integer>set=new HashSet<Integer>(); Random random=new Random(); while(set.size()<3){ int i=random.nextInt(1000); set.add(i); } 这个就是利用set的不重复性来创建三个不重复的整数。 但是我不知道该怎么样才能将数字带入替换student的ID属性
或许可以利用hashSet不可重复的特性
while(set1.size()<3){
set1.add(random.nextInt(1000));
}
当然最好是不影响原来的代码的情况下。