package zyz.app;
import java.util.Random;
public class RandomString {
public static final int LOWER = 0;
public static final int UPPER = 1;
public static final int INITIAL = 2;
public static final int MIX = 3;
private static final Random random = new Random();
public String randomString(int len, int type) {
switch (type) {
case INITIAL:
return len < 1 ? internalRandomString(1, UPPER) : internalRandomString(1, UPPER)
+ internalRandomString(len - 1, LOWER);
case MIX:
return internalRandomMixString(len);
default:
return internalRandomString(len, type);
}
}
private String internalRandomString(int len, int type) {
char a;
switch (type) {
case UPPER:
a = 'A';
break;
default:
a = 'a';
}
char[] cc = new char[len];
for (int i = 0; i < len; i++) {
cc[i] = (char) (random.nextInt(26) + a);
}
return new String(cc);
}
private String internalRandomMixString(int len) {
char[] cc = new char[len];
for (int i = 0; i < len; i++) {
cc[i] = internalRandomChar(new Random().nextInt(2));
}
return new String(cc);
}
private char internalRandomChar(int type) {
char a;
switch (type) {
case UPPER:
a = 'A';
break;
default:
a = 'a';
}
return (char) (random.nextInt(26) + a);
}
public static void main(String[] args) {
RandomString rs = new RandomString();
// test
for (int i = 0; i < 10; i++) {
int type = new Random().nextInt(4);
System.out.println("type:" + type + ",string:" + rs.randomString(20, type));
}
// performance test
long a = System.currentTimeMillis();
rs.randomString(100000, RandomString.LOWER);
long b = System.currentTimeMillis();
rs.randomString(100000, RandomString.MIX);
long c = System.currentTimeMillis();
System.out.println("-----------------------------------");
System.out.println("randomString(100000,lower) = " + (b - a) + "ms");
System.out.println("randomString(100000,mix) = " + (c - b) + "ms");
}
}
posted on 2007-05-30 11:09
apai 阅读(98)
评论(0) 编辑 收藏 所属分类:
java