PackageXiangmu;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;ImportJava.util.Random; Public classtestcollection {/** List Sort by defining the Collections.sort () method for a string generic * Creates a string generic list, inserting a random string of no more than 10*/ /** * @paramargs*/ Public voidTestSort1 () {List<String> stringlist=NewArraylist<string>(); Random Random=NewRandom (); String k= "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //add 10 different random strings for(inti=0;i<10;i++) {StringBuffer str=NewStringBuffer (); intStringlength=random.nextint (10) +1; Do{ for(intj=0;j<stringlength;j++){ intNumber=Random.nextint (K.length ()); Str.append (K.charat (number)); } } while(Stringlist.contains (Str.tostring ()));//Call the Stringlist.contains () method to pass the string inStringlist.add (Str.tostring ());//add a string to Stringlist and call the Stringlist.add () methodSystem.out.println ("Add string successfully:" +str); } System.out.println ("-------------------------before sorting"); //to traverse with foreach for(String string:stringlist) {System.out.println ("Element:" +string); } collections.sort (stringlist);//call Collections.sort () to sortSystem.out.println ("-------------------------after sorting"); for(String string:stringlist) {System.out.println ("Element:" +string); } } Public Static voidMain (string[] args) {//TODO auto-generated Method StubTestcollection ct=Newtestcollection (); Ct.testsort1 (); }}
Randomly generate a random string in Java that is not greater than 10 in length