1.使用TreeSet类实现定制排序(降序)
import java.util.*;
public class ert {
public static void main(String[] args) {
Set<Integer>set=new TreeSet<>();/*升序*/
set.add(-7);
set.add(-4);
set.add(3);
set.add(10);
set.add(6);
Iterator it=set.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
/*升序排法
Set<Integer>set2=new TreeSet<>(Compartor.reverseOrder());
*/
}
}
2.运用Hashset打印一个图书发票
import java.util.Objects;
/*创建构造方法*/
public class bookself {
String name;
String author;
double price;
public bookself(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
bookself bookself = (bookself) o;
return name.equals(bookself.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
/*测试类排序*/
public class booker {
public static void main(String[] args) {
Set<bookself>set=new HashSet();
bookself p1=new bookself("JAVA入门到精通第三版","明日科技著编",59.8);
bookself p2=new bookself("JAVA Web入门到精通","明日科技著编",67.8);
bookself p3=new bookself("JAVA从入门到精通<实例版>","明日科技著编",69.8);
set.add(p1);
set.add(p2);
set.add(p3);
Iterator<bookself>it=set.iterator();
System.out.print("书名\t"+" 作者\t"+" 价格\t"+"\n");
System.out.println("----------------------------------------------------\n");
while (it.hasNext()){
bookself its= (bookself) it.next();
System.out.println(its.getName()+"\t"+its.getAuthor()+"\t"+its.price+"\n");
}
}
}