HashMap的存储

定义:HashMap中每一个键只能映射一个键,当有重复的键的时候不会重复创建新的映射关系;而是使用先前的key。


实例代码1

package Test_10;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test {
    public void  testHashMap(){
        Map<String,String> hashMap = new HashMap<String, String>();
        hashMap.put("aaa", "111");
        hashMap.put("aaa", "222");

        Iterator iterator =  hashMap.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry entry =  (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            System.out.println(key+":"+value);
        }
    }
    public static void main(String[] args){
        Test t1 = new Test();
        t1.testHashMap();
    }
}

运行结果:

aaa:222


对象作为key

package Test_10;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 对象作为key
 * @author msi
 *
 */
class Person{
    String id;
    String name;

    public Person(String id,String name){
        this.id = id;
        this.name = name;
    }

    public String toString(){
        return "id="+id+",name"+name;
    }
}
public class Test {
    public void  testHashMap(){
        Map<Person,String> hashMap = new HashMap<Person, String>();
        Person p1 = new Person("111","name1");
        Person p2 = new Person("111","name1");
        hashMap.put(p1, "I am person1");
        hashMap.put(p2, "I am person2");

        Iterator iterator =  hashMap.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Person, String> entry =(Map.Entry<Person, String>)iterator.next();
            Person key= entry.getKey();
            String value = entry.getValue();

            System.out.println(key+":"+value);
        }
    }
    public static void main(String[] args){
        Test t1 = new Test();
        t1.testHashMap();
    }
}

运行结果:

id=111,namename1:I am person1
id=111,namename1:I am person2


这里写图片描述

这里写图片描述


HashMap中的put函数:

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
   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
    评论
当使用HashMap存储自定义类对象时,需要确保对象的唯一性。为了实现这一点,需要重写自定义类的hashCode()和equals()方法。 重写hashCode()方法是为了确保不同的对象具有不同的哈希码,从而在HashMap中能够正确地定位到对应的存储位置。 重写equals()方法是为了比较两个对象是否相等。在HashMap中,当发生哈希冲突时,会通过equals()方法来判断两个对象是否相等。 下面是一个示例,演示了如何在HashMap存储自定义类对象: ```java import java.util.HashMap; class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } // 重写hashCode()方法 @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } // 重写equals()方法 @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } public class HashMapExample { public static void main(String[] args) { HashMap<Student, Integer> studentMap = new HashMap<>(); Student student1 = new Student(1, "Alice"); Student student2 = new Student(2, "Bob"); studentMap.put(student1, 90); studentMap.put(student2, 85); System.out.println(studentMap.get(student1)); // 输出:90 System.out.println(studentMap.get(student2)); // 输出:85 } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值