求帮忙看下这段代码为什么有时候会生成一个空的字符串添加到stl集合里?

public void testSort3(){

String string = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz";

List<String> stl = new ArrayList<String>();

Random random = new Random();

for(int j = 0;j < 10;j++){

char e;

String st = "";

for(int i = 0;i < random.nextInt(string.length());i++){

//判断stl是否包含上一个生成的字符串,如果为true,

//则重新循环生成,如果为false,则添加到stl

do{

e = string.charAt(random.nextInt(string.length()));

st = st + e;

}while(stl.contains(st));

}

stl.add(st);

}

System.out.println("----------排序前---------");

for (String string2 : stl) {

System.out.println("字符串:"+string2);

}

Collections.sort(stl);

System.out.println("----------排序后---------");

for (String string2 : stl) {

System.out.println("字符串:"+string2);

}

}

输出结果:

----------排序前---------

字符串:1YeO69qEpz

字符串:Ox8EHbOcmmunkF

字符串:GajsKoNIq79

字符串:LJJwdreXtL4hr

字符串:YAxE

字符串:VtpRe0MFa

字符串:62pxdYnYuGI9jObYphtDH

字符串:

字符串:dWR02Q

字符串:KavtY2r

----------排序后---------

字符串:

字符串:1YeO69qEpz

字符串:62pxdYnYuGI9jObYphtDH

字符串:GajsKoNIq79

字符串:KavtY2r

字符串:LJJwdreXtL4hr

字符串:Ox8EHbOcmmunkF

字符串:VtpRe0MFa

字符串:YAxE

字符串:dWR02Q


慕哥7677898
浏览 1200回答 3
3回答

慕的地8582982

XAPTVLUKTDTBJMRNJHXMDGMOQUDNXAKNQZVIYJSVKGDMJMPFPZVSZKHNWMPYCLOCMVVXNWFPFOXTDWFUDAPYODBEHXARHXHRZWYXMIZIYUEMKAHQZWLUKNPTPZFPZVLCYAKUGCEBEURGWTPFOXNJGJZBYAAQSVYVLUKNVUQTJMVEUQGDFUQZKTCYZPZSUJYBXBXGWZTOXBYODNUDAAWQAUOFWSCIEUPMJMWZBFTIKHDNJEAWMPBORTDUXZPMVKOKFIYUKUKILHYVEBENPSPLUEAWGJZBEBJFUKOKFIKBKTXFORVYPEPSBDLBEHYTPFIMVEHCYOEHRHVYUYUXNEGWZMPEUKAQEAXUZPLUKVEHQNPKWUVPJDUTTVZORBUOBCOLSCGFNRFWMDNKYHJROKAJMPMEHXVRIMCSWFHUKNXHXACFBGVEAQAJZVLPCVSJCVHXAEKJLLDDUZKGAKFVBGUBLYBOWWLJZXEXYIUUWSLIPDQAJNNEAGOYOVFUILZWGHNKPWFTGBLPFPMMJSQQOBFJQQVVFPELIVKHUVLCGAMCXYGQPJGJRJGQQHBZTAPYUBWQXSTAXKEHPZJRVFUUOMRHBSKOOSRDDPTFUBJDGQTHVROIROSLUMACCOYJLIZTZQCYZZNCMZVGNIFVLYZVJJDQZSTDNGULERPJRDSVSCATNHMGCTKOUOBECZJNQOFFMVFZUAXUHVNQKUYRHELECSRRLYLJFUEKORGXYQWVAHNNZTXUROECCJZTDRORTFMMTERYYFFPCSJCJATWNDNNULVOBEIPTZFQXHASDGENDTWQQIODXOPOZISTJNNUHRLHAKACSVFVVLIIFMWGFDXVLLJJQVPYCZLPCSTJOTPTIMGWGNWGADLM

raynZhang

因为do-while循环是先执行一次再进行判断,可以改成while循环运行试下看下结果
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java