慕函数1299684
2019-02-13 21:43
public void testSort3() {
List<String> stringList =new ArrayList<String>();
String k;
for(int i = 0; i< 10; i++) {
do {
k = generateString(10);
}while(stringList.contains(k));
stringList.add(k);
}
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);
}
}
/**
* 返回随机字符串方法
* @param args
*/
public static String generateString(int length) //参数为返回随机数的长度
{
StringBuffer sb = new StringBuffer();
Random random = new Random();
Random random2 =new Random();
int j;
j= random2.nextInt(length);
for (int i = 0; i < j; i++)
{
j= random2.nextInt(length);
sb.append(allChar.charAt(random.nextInt(allChar.length())));
}
return sb.toString();
}
package com.imooc.collection;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;public class CollectionsTest { public List<Integer> listInteger; public CollectionsTest() { this.listInteger = new ArrayList<Integer>(); } public void testSortInteger() { Random random = new Random(); Integer k; for (int i = 0; i < 10; i++) { do { k = random.nextInt(100); } while (listInteger.contains(k)); listInteger.add(k); System.out.println("成功添加整数:" + k); } System.out.println("------------排序前----------------------"); for (Integer integer : listInteger) { System.out.println("元素:" + integer); } Collections.sort(listInteger); System.out.println("------------排序后----------------------"); for (Integer integer : listInteger) { System.out.println("元素:" + integer); } // listInteger.sort(c); } public String productString(int strLength) { Random random = new Random(); Integer k; String stringSource ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String temp = ""; for(int i = 0;i < strLength;i++) { k = random.nextInt(62); temp += stringSource.charAt(k); } return temp; } public void testSortString() { List<String> listString = new ArrayList<String>(); String s = ""; for(int i = 0;i < 10;i++) { do { s = productString(10); listString.add(s); System.out.println("成功添加字符串:"+s); }while(!(listString.contains(s))); } System.out.println("-------------排序前----------------"); for (String string : listString) { System.out.println("元素:"+string); } Collections.sort(listString); System.out.println("-------------排序后----------------"); for (String string : listString) { System.out.println("元素:"+string); } } public static void main(String[] args) { // TODO Auto-generated method stub CollectionsTest st = new CollectionsTest(); //st.testSortInteger(); st.testSortString(); }}
Java入门第三季
409792 学习 · 4340 问题
相似问题