标签:compareto iter 整数 asn 随机数 inf random rgs set集合
1.使用TreeSet集合生成一个不重复随机数组,该数组包含10个100以内的随机整数。输出该随机数组。
4 import java.util.Iterator; 5 import java.util.TreeSet; 6 7 public class Test { 8 public static void main(String[] args) { 9 int x; 10 int arr []=new int [20]; 11 TreeSet<Integer> set =new TreeSet<Integer>(); 12 13 int d=0; 14 while(d<10){ 15 x=(int)(Math.random()*100); 16 if(set.add(x))//TreeSet是去重复的集合,集合中没有的返回true 17 d++; 18 } 19 /* 20 while(set.size()<10){ 21 x=(int)(Math.random()*100); 22 set.add(x); 23 } 24 */ 25 int i=1; 26 Iterator<Integer>it=set.iterator(); 27 while(it.hasNext()){ 28 int t=it.next(); 29 arr[i]=t; 30 i++; 31 } 32 for(i=1;i<=10;i++) 33 System.out.print(arr[i]+" "); 34 } 35 }
2.创建一个Student类,使用比较器Comparator,根据学号进行对象排序。 4 import java.util.Comparator; 5 import java.util.Iterator; 6 import java.util.TreeSet; 7 class Student { 8 private String name; 9 private String id; 10 public Student(){ 11 } 12 public Student(String name,String id){ 13 this.name=name; 14 this.id=id; 15 } 16 public String getName() { 17 return name; 18 } 19 public String getId() { 20 return id; 21 } 22 } 23 class DescSort implements Comparator<Student> { 24 25 public int compare(Student s1, Student s2) { 26 if(s1.getId().compareTo(s2.getId())>0) 27 return -1; 28 else if(s1.getId().compareTo(s2.getId())<0) 29 return 1; 30 else return 0; 31 } 32 } 33 public class Test { 34 public static void main(String[] args) { 35 Comparator<Student> comp=new DescSort(); 36 TreeSet<Student> t=new TreeSet<Student>(comp); 37 t.add(new Student("小赵","11517447")); 38 t.add(new Student("小王","11517432")); 39 t.add(new Student("小明","11517413")); 40 t.add(new Student("小红","11517402")); 41 t.add(new Student("小李","11517425")); 42 Iterator<Student>it=t.iterator(); 43 while(it.hasNext()){ 44 Student stu=it.next(); 45 System.out.println(stu.getName()+"的学号是"+stu.getId()); 46 } 47 } 48 }
输出结果:
标签:compareto iter 整数 asn 随机数 inf random rgs set集合
原文地址:https://www.cnblogs.com/diandianer/p/10140196.html