用 java 编写程序时,取随机数通常有两种方法,1. 采用 Ramdom(), 2. 采用 Math.random(), 其实这两种方式基本差不多,写一个简单的例子,从一个list 中随机抽取一个记录.
方法一, 采用 Ramdom()
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomTest {
private Random random = new Random();
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Boy");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
RandomTest obj = new RandomTest();
for(int i = 0; i < 10; i++){
System.out.println(obj.getRandomList(list));
}
}
public String getRandomList(List<String> list) {
//0-4
int index = random.nextInt(list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
第二种方法:
public class MathRandomExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
MathRandomExample obj = new MathRandomExample();
for(int i = 0; i < 10; i++){
System.out.println(obj.getRandomList(list));
}
}
public int getRandomList(List<Integer> list) {
//Math.random() = greater than or equal to 0.0 and less than 1
//0-4
int index = (int)(Math.random()*list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
用这两种方式,都能很方便的得到随机数。
方法一, 采用 Ramdom()
程序代码
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomTest {
private Random random = new Random();
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Boy");
list.add("Cat");
list.add("Dog");
list.add("Elephant");
RandomTest obj = new RandomTest();
for(int i = 0; i < 10; i++){
System.out.println(obj.getRandomList(list));
}
}
public String getRandomList(List<String> list) {
//0-4
int index = random.nextInt(list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
第二种方法:
程序代码
public class MathRandomExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
MathRandomExample obj = new MathRandomExample();
for(int i = 0; i < 10; i++){
System.out.println(obj.getRandomList(list));
}
}
public int getRandomList(List<Integer> list) {
//Math.random() = greater than or equal to 0.0 and less than 1
//0-4
int index = (int)(Math.random()*list.size());
System.out.println("\nIndex :" + index );
return list.get(index);
}
}
用这两种方式,都能很方便的得到随机数。