Java入门第三季_随机字符串排序
// 对各种类型的List进行排序
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
// sortList()
public void sortList() {
// 基本类型做泛型要使用包装类
List<Integer> integerList = new ArrayList<Integer>();
Random random = new Random();
Integer k;
// 10个100以内不重复整数
for (int i=0;i<10;i++) {
do {k = random.nextInt(100);} while (integerList.contains(k));
integerList.add(k);
}
System.out.println("添加成功:10个100以内不重复整数");
// 未排序前
System.out.print("未排序前:");
for (Integer integer : integerList) System.out.print(integer+" ");
// 排序之后
System.out.print("\n排序之后:");
Collections.sort(integerList);
for (Integer integer : integerList) System.out.print(integer+" ");
}
// sortString() 0-9 A-Z a-z
public void sortString() {
List<String> sl = new ArrayList<String>();
sl.add("Apple");
sl.add("Nike");
sl.add("Google");
System.out.println("\n添加成功:3个字符串");
System.out.print("未排序前:");
for (String string : sl) {
System.out.print(string+" ");
}
Collections.sort(sl);
System.out.print("\n排序之后:");
for (String string : sl) {
System.out.print(string+" ");
}
}
// sortString() v2
public void homework() {
List<String> hw = new ArrayList<String>();
// 10条字符串
for (int i=0; i<10; i++) {
// 长度10以内
String s = ""; // 方法里面的变量要赋初值!!!
do {
Random r = new Random();
int digit = r.nextInt(10);
for (int j=0; j<digit; j++) {
// 随机生成字符
int a = 0;
do {
a = r.nextInt(75)+48;
} while ( (a>57&&a<65) || (a>90&&a<97) );
char b = (char) a;
s+=b;
}
} while (hw.contains(s));
hw.add(s);
}
System.out.println("\n未排序的10个随机字符串:");
for (String string : hw) System.out.println(string);
System.out.println("排序后的10个随机字符串:");
Collections.sort(hw);
for (String string : hw) System.out.println(string);
}
public static void main(String[] args) {
CollectionsTest ct = new CollectionsTest();
ct.sortList();
ct.sortString();
ct.homework();
}
}
相关文章