JAVA Set集合练习

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");



        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值