Java之HashSet练习

  1. 案例题目描述:

    完成手机超市管理系统功能。

    2.案例完成思路要求:

定义一个手机类,包含手机品牌,价格,型号,封装该类的属性,并定义该类的有参构造方法实现对属性的赋值

      a.创建3个手机类对象。并给各对象数据赋值。

      b.将3个手机对象依次保存到HashSet中。

     c.将HashSet中的元素使用迭代器换行输出。

     d.将价格低于2000元的手机,价格提升500元。

     e.打印集合中三星手机的个数。


public class Phone {
	private String brand;
	private double price;
	private String model;
	public Phone(String brand, double price, String model) {
		super();
		this.brand = brand;
		this.price = price;
		this.model = model;
	}
	
	public void show() {
		System.out.println("品牌:"+brand+"\t价格"+price+"\t型号"+model);
	}
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
}

public class TestPhone {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet<Phone> hash=new HashSet<Phone>();
		hash.add(new Phone("三星", 3458, "Galaxy"));
		hash.add(new Phone("iphone", 2800, "苹果"));
		hash.add(new Phone("三星", 3499, "note 3"));
		
		Iterator<Phone> it=hash.iterator() ;
		while(it.hasNext()) {
			it.next().show();
		}
		
		System.out.println("\n将价格低于3000元的手机,价格提升500元。\n");
		int num=0;
		
		it=hash.iterator() ;
		while(it.hasNext()) {
			Phone phone=it.next();
			if(phone.getPrice()<3000) {
				phone.setPrice(phone.getPrice()+500);
			}
			if(phone.getBrand().equals("三星"))
				num++;
			phone.show();
		}
		
		System.out.println("三星手机个数:"+num);
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值