其中Math.random()方法是一个可以产生[0.0,1.0]区间内的一个双精度浮点数的方法
如:
产生一个100以内的整数:int x=(int)(Math.random()*100)
又如:
产生一个1-50之间的随机数:int x=1+(int)(Math.random()*50)
也可以使用通用创建对象来获取:
Random random = new Random()
random.nextInt(x)
产生一个0到x-1的正数,如果想产生浮点数有Random类的nextFloat方法,总之nextXXX方法是用来产生随机数的。
public class Zhuq {public static void main(String[] args) {
List<Person>listP=new ArrayList<Person>()
listP.add(new Person("小李", "1", 200))
listP.add(new Person("小王", "2", 210))
listP.add(new Person("小赵", "3", 230))
listP.add(new Person("小孙", "4", 100))
listP.add(new Person("小钱", "5", 3))
listP.sort(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return (((Person)o1).count)*(Math.random()*10+1)>(((Person)o2).count)*(Math.random()*10+1)?-1:1
}
})
System.out.println(listP)
}
}
class Person {
String personName
String id
int count
public Person(String personName, String id, int count) {
super()
this.personName = personName
this.id = id
this.count = count
}
@Override
public String toString() {
return "Person [personName=" + personName + ", id=" + id + ", count=" + count + "]"
}
}
//本质还是随机数
好好的看一下就知道为什么list的长度与count 相同时,总是出现死循环 。你在int[] a=new int[count]这一步操作时,数组a中的数据全部默认为0,而int rs=ran.nextInt(list.size())返回的值是0到list.size()-1的数。当list的长度与count 相同时,在产生最后一个随机数时,只能产生0,可是0在数组a中又存在了,所以就死循环了。
编程时,多注意边界问题。