HashSet的add方法-指定自建类的属性标识对象

应用实例:
创建一个Student类的数组,每个Student对象由学号唯一标识。
类Student,包含字段:学号no:int;姓名name:String;

public class Main{
	public static void main(String[] args) {
		HashSet<Student> stuSet = new HashSet<Student>();//构造HashSet对象,构造方法中实际调用的HashMap<>();    
		int[] nos = new int[] {3,2,1,1};//学号单元,重复学号用于测试
		//姓名单元
		String[] names = new String[] {"cuizhenyu","tiangang","dingchangqing","zhangfeng"};
		//创建对象,并加入到HashSet对象中
		for(int i=0;i<3;i++){
			int no = nos[i];
			String name = names[i];
			Student s = new Student(no,name);
			stuSet.add(s);
			/*
		 	* HashSet 的add方法调用过程是
	 		* HashSet中的add方法→HashMap中的put方法→(HashMap中的hash方法)HashMap中的putVal
	 		* 为了指定对象的某个特定属性用于hash
	 		* 需重写hashCode()方法和equals()方法
	 		* 若比较的变量是基本类型变量,需将其转换为基本类型类对象
	 		*/
		}
		for(Student s:stuSet) System.out.print(s.no+" ");//输出数据
}
class Student {
	public int no;//学号
	public String name;//姓名
	public Student(int no, String name) {
		this.no = no;
		this.name = name;
	}
	
	@Override
	public int hashCode() {
		//重载hashCode()方法,指定的hash的属性是基本类型,需转换成对应的基本类型类的对象
		Integer no = new Integer(this.no);
		return no.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		//重载equals()方法,按需求指定比较的属性为学号no;
		if(obj instanceof Student) {
			Student s = (Student)obj;
			return this.no==s.no;
		}
		return false;
	}
}

输出

1 2 3//相同学号的对象没有重复添加

调用过程源码:

 public boolean add(E e) {
        return map.put(e, PRESENT)==null;
        //e是添加的元素,
        //PRESENT是个哑值,声明如下:
        //private static final Object PRESENT = new Object();
    }
   public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

java文档中对hashCode()约定中描述到只要不修改对象的equals()方法,并且两个对象是相等的,那么必须产生相同的整数(hash)。
所以要让自定义类的hash是根据指定属性产生的,就要更改equals()方法,使比较的对象是指定的那个参数。

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HashSetJava集合框架中的一个类,它实现了Set接口,可以用于存储一组没有顺序、不重复的元素。下面介绍HashSet常用方法的使用。 1. add(Object obj):向集合中添加元素。 示例代码: ```java Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("orange"); System.out.println(set); // 输出 [orange, banana, apple] ``` 2. remove(Object obj):从集合中删除指定元素。 示例代码: ```java Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("orange"); set.remove("banana"); System.out.println(set); // 输出 [orange, apple] ``` 3. contains(Object obj):判断集合中是否包含指定元素。 示例代码: ```java Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("orange"); System.out.println(set.contains("banana")); // 输出 true System.out.println(set.contains("pear")); // 输出 false ``` 4. size():获取集合中元素的个数。 示例代码: ```java Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("orange"); System.out.println(set.size()); // 输出 3 ``` 5. clear():清空集合中的所有元素。 示例代码: ```java Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("orange"); set.clear(); System.out.println(set); // 输出 [] ``` 6. isEmpty():判断集合是否为空。 示例代码: ```java Set<String> set = new HashSet<String>(); System.out.println(set.isEmpty()); // 输出 true set.add("apple"); System.out.println(set.isEmpty()); // 输出 false ``` 以上就是HashSet常用方法的使用,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值