import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Sort2 {
/**
- 1.获取待选随机数列表字符串random长度; 2.获取随机数length1的长度,并判断长度不等于0;
- 3.创建一个char[]ct数组,随机获取字符串random的其中一个字符并加入char[]中
- 4.将char[]通过String类的valueOf()方法转成字符串
- 5.判断ArrayList中有无当前随机数,若有,则重新获取随机数,若无,则加入ArrayList中;
-
6.利用List中的Iterator()方法迭代输出List中的随机数
/
public void Sort2Test() {
// String[] random=new
// String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
ArrayList<String> al = new ArrayList<String>();
String random = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";// 随机数列表
int a = random.length();// 待随机数索引长度
String st = "";// 随机数名字
while (true) {
int length1 = 0;// 随机数长度
// 创建一个length2获取值并判断不等于0的长度值
int length2 = (int) (Math.random() 10);
if (length2 != 0) {
length1 = length2;// 获取随机数长度
}
char[] ct = new char[length1];// 创建一个char数组
for (int i = 0; i < length1; i++) {
ct[i] = random.charAt((int) (Math.random() * a));
st = String.valueOf(ct);
}
if (al.contains(st)) {
continue;
}
al.add(st);
System.out.println("将要添加字符串:" + st);
if (al.size() == 10) {
break;
}
}
Iterator<String> it = al.iterator();
System.out.println("----------------------排序前--------------------------");
while (it.hasNext()) {
System.out.println("元素:" + it.next());
}
Collections.sort(al);
Iterator<String> it2 = al.iterator();
System.out.println("----------------------排序后--------------------------");
while (it2.hasNext()) {
System.out.println("元素:" + it2.next());
}
}public static void main(String[] args) {
Sort2 sort2 = new Sort2();
sort2.Sort2Test();}
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章