/**
需求: * 创建一个String泛型的list,往其中添加十条随机的字符串
* 每条字符串长度为10以内的随机整数
* 每条字符串的每个字符都为随机生成的字符,字符可以重复
* 每条随机字符串不可重复
*/
package cn.String.Day.collection;
import java.util.*;
/**
* Created by Void on 2017/7/11.
* 1、通过collections.sort方法,对integer泛型的list进行排序
* 2、对String泛型的list进行排序
* 3、对其他类型泛型的list进行排序,以Student为例
*/
public class arrayListSort {
public String random;
public Set<?> stringSet;
/**
* 创建一个integer泛型的list,插入十个100以内的不重复的随机整数,调用collection.sort方法对其进行排序
*/
public void testSortInteger(){
List<Integer> integerList = new ArrayList<Integer>();
//插入十个100以内的不重复随机整数
Random rd = new Random();
Integer k;
for (int i = 0;i<10;i++){
do {
k = rd.nextInt(100);
}while (integerList.contains(k));//循环进do判断条件是否为true 否则不出循环(while中判断队列中是否包含该元素)
integerList.add(k);
}
for (Integer intg:integerList){
System.out.println(intg);
}
System.out.println("=======================");
Collections.sort(integerList);
for (Integer intg:integerList){
System.out.println(intg);
}
}
/**
* 对String泛型的list进行排序
* 创建一个String泛型的list,添加三个乱序的String元素
* 调用sort方法,再次输入排序后的顺序
*/
public void testStringSort(){
List<String> stringList = new ArrayList<String>();
stringList.add("Google");
stringList.add("Apple");
stringList.add("Microsoft");
Collections.sort(stringList);
for (String s:stringList
) {
System.out.println(s);
}
for (int i = 0 ; i<stringList.size();i++) {
System.out.println(stringList.get(i));
}
}
/**
* 对String泛型的list进行排序
* 创建一个String泛型的list,往其中添加十条随机的字符串
* 每条字符串长度为10以内的随机整数
* 每条字符串的每个字符都为随机生成的字符,字符可以重复
* 每条随机字符串不可重复
*/
public void testStringIntSort(){
Random rd = new Random();
//定义一个随机数的数组
char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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'};
//使用字符串缓冲区用来把数组中的字符变成字符串添加到缓冲区中
// StringBuilder sb = new StringBuilder();
// //取十条数据
// for (int i = 0; i<10;i++){
// //每条字符串长度不超过10
// for (int y = 0;y<10;y++) {
// if (y!=9)
// sb.append(chr[rd.nextInt(62)]);
// else
// sb.append(chr[rd.nextInt(62)]+",");
// }
// }
// String string = sb.toString();//转换成字符串
// String[] arrayS = string.split(",");
// stringSet = new TreeSet<Object>(Arrays.asList(arrayS));//保证字符串不重复,但是会丢数据!
// Iterator it = contains.iterator();
// while (it.hasNext()){
// random = (String) it.next();
// System.out.println(random);
// }
StringBuilder sb = new StringBuilder();
List<String> contains = new ArrayList<String>();
//取十条数据
for (int i = 0; i<10;i++){
//每条字符串长度不超过10
for (int y = rd.nextInt(10);y<10;y++) {
if (y==9)
contains.add(sb.append(chr[rd.nextInt(62)]).toString());
sb.append(chr[rd.nextInt(62)]);
}
sb.delete(0,sb.length());
}
Collections.sort(contains);
for (String s:contains){
System.out.println(s);
}
}
public static void main(String[] args) {
arrayListSort als = new arrayListSort();
// als.testSortInteger();
// als.testStringSort();
als.testStringIntSort();
}
}