java生成随机字符串

时间:2022-08-06 20:45:05

学习java comparable特性时候,定义如下Student类,需要需要随机添加学生姓名以及学号和成绩,这是java如何随机生成名字,根据我的查询,我找到目前java库支持两种方法。

1. org.apache.commons.lang3.RandomStringUtils类,他支持方法可以到RandomStringUtils查询,其中有一个方法:

public static java.lang.String random(int count,
int start,
int end,
boolean letters,
boolean numbers)

这个方法有多个重载,我们采用以上函数,count参数表示生成字串长度,start,end表示ASCII码列表中选取字符开始和结束位置,布尔型数据letters表示alphabet是否出现,numbers表示数字是否出现。

            tmpName = RandomStringUtils.random(10, 20, 110, true, true);
System.out.println("Name generated randomly: " + tmpName);

我们可以修改函数参数参数,调用不同函数实现不同功能,例如只输出字母后者仅仅输出数字。

附注:

java中支持生成UUID,UUID一共128位bit,通过太网卡地址、纳秒级时间、芯片ID码和许多可能的数字,生成在一个时间系统里面独一无二的标识,所以我们可以使用他来生成数据库主键,例如:

            valkey = UUID.randomUUID().toString();

以上两种语言应用实例如下:

import java.util.*;

import org.apache.commons.lang3.RandomStringUtils;

/**
* Created by carl on 11/7/15.
*/
class Student implements Comparable<Student> {
private String name;
private String key;
private float score;
private int age; public Student(String key, String name, float score, int age) {
this.key = key;
this.name = name;
this.score = score;
this.age = age;
} @Override
/*
public int compareTo(Student ano) {
if (this.score < ano.score)
return -1;
if (this.score > ano.score)
return 1;
else {
if (this.age > ano.age)
return 1;
if (this.age < ano.age)
return -1;
else
return 0;
}//else
}//compareTo
*/
public int compareTo(Student ano){
return (int)(this.score - ano.score);
} public static List<Student> getStudents(){ List<Student> col = new ArrayList<Student>(); Random rand = new Random();
String valkey;
int valAge, valScore;
String valName;
for (int i = 0; i < 10; i++) {
valkey = UUID.randomUUID().toString();
valName = RandomStringUtils.random(10, 20, 110, true, true);
valAge = rand.nextInt(80);
valScore = rand.nextInt(80);
col.add(new Student(valkey,valName, valAge, valScore));
} return col;
} public String getName(){
return name;
} public float getScore() {
return score;
} public int getAge() {
return age;
} @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", key='" + key + '\'' +
", score=" + score +
", age=" + age +
'}';
}
}//Student public class ClassSort {
public static void main(String []args) {
//Student stu1 = new Student("wen", 90, 17);
//Student stu2 = new Student("mike", 90, 18);
//System.out.print("res:" + stu1.compareTo(stu2));
List<Student> grade1 = Student.getStudents();
Iterator<Student> iter = grade1.iterator();
while(iter.hasNext()) {
//iter.next();
System.out.println(iter.next().toString());
}
}
}