生成隨機字串並排序

wh7577發表於2021-09-09

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 Liststudentlist=new ArrayList();//學生物件
public Liststringlist=new ArrayList();

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 String str="abcdefghilmnopqrstuvwxyzABCDEFGHILMNOPQRSTUVWXYZ0123456789";
int b=str.length();
StringBuilder sb=new StringBuilder();
int d=random.nextInt(10);
for(int a=0;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 {

@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();
}
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2480/viewspace-2807994/,如需轉載,請註明出處,否則將追究法律責任。

相關文章