public void testSort2(){ List<String> stringList = new ArrayList<String>(); Random random = new Random(); String basic = "0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(int i=0;i<10;i++){ StringBuffer sb = new StringBuffer(); int num = random.nextInt(10)+1; do{ for(int j=0;j<num;j++){ int number = random.nextInt(basic.length()); sb.append(basic.charAt(number)); } }while(stringList.contains(sb)); String stringSb =sb.toString(); stringList.add(stringSb); System.out.println("添加了字符串:"+stringSb); } System.out.println("------------排序前-------------"); for (String string : stringList) { System.out.println("元素:"+string); } Collections.sort(stringList); System.out.println("------------排序后-------------"); for (String string : stringList) { System.out.println("元素:"+string); } }
我有个问题想要问你一下
int num = random.nextInt(10)+1;
这里面在任意规定字符串的长度的时候为什么不能用
int num = random.nextLine(10)+1;
而且我用的时候还报错了?
代码给些注释呗!
对不起,没看全,没问题,是我理解错了
你去重有点问题;
for(int j=0;j<num;j++){
do{
//取basic内任意下标
int number = random.nextInt(basic.length());
sb.append(basic.charAt(number));
}while(stringList.contains(sb));
}
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Collections;
public class listContainTest {
public List<String> dataList;
public List<Character> characterList;
public void initlizeCharacterList(){
//数字字符
for (Character c = '0'; c<='9'; c++){
characterList.add(c);
}
//大写字母
for (Character c = 'A'; c<='Z'; c++){
characterList.add(c);
}
//小写字母
for (Character c = 'a'; c<='z'; c++){
characterList.add(c);
}
}
/*
* list、set、map声明变量时,要在构造器中或其他地方进行初始化操作
*/
public listContainTest(){
dataList = new ArrayList<String>();
characterList = new ArrayList<Character>();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
listContainTest lct = new listContainTest();
lct.initlizeCharacterList();
Random rand = new Random();
for (int i=0; i<10; i++){
String stTemp = "";
do{
int k = rand.nextInt(9)+1;
for (int j=0; j<k; j++){
int ipos = rand.nextInt(lct.characterList.size());
stTemp += lct.characterList.get(ipos).toString();
}
//判断字符串是否在字符串列表中
}while(lct.dataList.contains(stTemp));
lct.dataList.add(stTemp);
}
//打印未排序字符串
System.out.println("---------未排序字符串---------------");
for (int i=0; i<10; i++){
System.out.println(lct.dataList.get(i));
}
//排序后字符串
System.out.println("---------排序后字符串---------------");
Collections.sort(lct.dataList);
for (int i=0; i<10; i++){
System.out.println(lct.dataList.get(i));
}
}
}