关闭

HashSet 实例

339人阅读 评论(0) 收藏 举报
分类:
package com.zyf.day24;

import java.util.HashSet;
import java.util.Iterator;

class Book{
	String name;
	double price;
    public Book(String name,double price) {
		// TODO Auto-generated constructor stub
    	this.name = name;
    	this.price = price;
	}
    
    @Override
    public String toString() {
    	// TODO Auto-generated method stub
    	return "[书名:" + this.name + " 价格:" + this.price + "]"; 
    }
    
    @Override
    public int hashCode() {
    	// TODO Auto-generated method stub
    	return this.name.hashCode();
    }
    
    @Override
    public boolean equals(Object obj) {
    	// TODO Auto-generated method stub
    	Book b = (Book) obj;
    	return this.name.equals(b.name);
    }
}
public class demo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        //不允许重复
		HashSet<Book> books = new HashSet<Book>();
		books.add(new Book("深入Javaweb",34));
		books.add(new Book("java神书",78));
		books.add(new Book("java神书",78));
//	    books.remove(new Book("java神书",78));
		
		//修改书名
		Iterator<Book> it = books.iterator();
		while(it.hasNext()){
			Book b = it.next();
			if(b.name.equals("java神书")){
				b.name = "java编程思想";
			}
		}
		//为什么改了名字后不能删除了!
		books.remove(new Book("java编程思想",78));
		System.out.println("集合的元素: "+ books);
		
		

	}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:126499次
    • 积分:4013
    • 等级:
    • 排名:第8195名
    • 原创:270篇
    • 转载:27篇
    • 译文:0篇
    • 评论:10条
    最新评论