继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

生成随机字符串并排序

什么鬼_呀你
关注TA
已关注
手记 21
粉丝 4
获赞 25

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class collectionstest2 {
public List<student>studentlist=new ArrayList<student>();//学生对象
public List<StringBuilder>stringlist=new ArrayList<StringBuilder>();

Random random=new Random();
//对类对象的排序(随机生成不同的ID排序)
public void test(){
int k,a,b,c,d,e;

        k=random.nextInt(10);

    studentlist.add(new student(k+"","bobay"));

        a=random.nextInt(10);
    if(a!=k){

    studentlist.add(new student(a+"","ann"));
    }else{this.random.nextInt();}
        b=random.nextInt(10);

    if(b!=k&&b!=a){
    studentlist.add(new student(b+"","ken"));
    }else{
        this.random.nextInt();
    }
        c=random.nextInt(10);
    if(c!=k&&c!=a&&c!=b){

    studentlist.add(new student(c+"","mike"));
    }else{
        this.random.nextInt();
    }
    System.out.println("-----------排序前------------");
    for(student s:studentlist){
        System.out.println("学生:"+s.id+" "+s.name);
    }
    Collections.sort(studentlist);
    System.out.println("-----------排序后------------");
    for(student s:studentlist){
        System.out.println("学生:"+s.id+" "+s.name);
    }

}
//对字符串排序

public void stringSort(){

for(int i=0;i<10;i++){//控制字符串个数
String str="abcdefghilmnopqrstuvwxyzABCDEFGHILMNOPQRSTUVWXYZ0123456789";
int b=str.length();
StringBuilder sb=new StringBuilder();
int d=random.nextInt(10);
for(int a=0;a<d;a++){
sb.append(str.charAt(random.nextInt(b)));
}
sb.toString();
stringlist.add(sb);

}
System.out.println("--------------排序前--------------");
for(StringBuilder string:stringlist){
System.out.println("字符:"+string);
}
Collections.sort(stringlist, new comparatortest())
;//这里需要新建类创建一个comparator方法:
/*
import java.util.Comparator;

public class comparatortest implements Comparator<StringBuilder> {

@Override
public int compare(StringBuilder o1, StringBuilder o2) {
    // TODO Auto-generated method stub
    return o1.toString().compareTo(o2.toString());
}

}

*/
System.out.println("--------------排序后--------------");
for(StringBuilder string:stringlist){
System.out.println("字符:"+string);
}
}
public static void main(String[] args) {
collectionstest2 c1=new collectionstest2();
c1.test();
c1.stringSort();
}
}

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP