java-14习题

 .使用TreeSet集合生成一个不重复随机数组,该数组包含10个100以内的随机整数。输出该随机数组。 

 import java.util.Iterator;
import java.util.TreeSet; public class Test {
public static void main(String[] args) {
int x;
int arr []=new int [];
TreeSet<Integer> set =new TreeSet<Integer>(); int d=;
while(d<){
x=(int)(Math.random()*);
if(set.add(x))//TreeSet是去重复的集合,集合中没有的返回true
d++;
}
/*
while(set.size()<10){
x=(int)(Math.random()*100);
set.add(x);
}
*/
int i=;
Iterator<Integer>it=set.iterator();
while(it.hasNext()){
int t=it.next();
arr[i]=t;
i++;
}
for(i=;i<=;i++)
System.out.print(arr[i]+" ");
}
}
 .创建一个Student类,使用比较器Comparator,根据学号进行对象排序。

 import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
class Student {
private String name;
private String id;
public Student(){
}
public Student(String name,String id){
this.name=name;
this.id=id;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
class DescSort implements Comparator<Student> { public int compare(Student s1, Student s2) {
if(s1.getId().compareTo(s2.getId())>)
return -;
else if(s1.getId().compareTo(s2.getId())<)
return ;
else return ;
}
}
public class Test {
public static void main(String[] args) {
Comparator<Student> comp=new DescSort();
TreeSet<Student> t=new TreeSet<Student>(comp);
t.add(new Student("小赵",""));
t.add(new Student("小王",""));
t.add(new Student("小明",""));
t.add(new Student("小红",""));
t.add(new Student("小李",""));
Iterator<Student>it=t.iterator();
while(it.hasNext()){
Student stu=it.next();
System.out.println(stu.getName()+"的学号是"+stu.getId());
}
}
}

输出结果:

java-14习题

上一篇:2018-8-10-win10-uwp-商业游戏-


下一篇:[转]IIS应用程序池经典模式转集成模式解决方案