java 集合(Map3)

Map接口下的实现类:

HashMap

1.存储原理:

  向HashMap中添加元素时,首先会调用hashCode(),算的哈希值,然后

  算出该元素在哈希表中的存储位置。

情况1

情况2(java  集合(Map2)写过了)

2.有必要时要重写 hashCode(), equals()

import java.util.*;

public class ex12 {
    public static void main(String[] args) {
      HashMap map = new HashMap();
        map.put(new Person(110, "Tom"), 001);
        map.put(new Person(220, "Jack"), 002);
        map.put(new Person(330, "TNT"), 003);
        map.put(new Person(110, "Bat"), 004);//   如果出现了相同的键,那么后添加的会取代原来的,可以观察运行结果  Tom 没有被输出
        System.out.println(map);

        }
    }

class Person{
    int id;
    String name;

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

    @Override
    public String toString() {
        return "[ id = " + this.id + ", name = " + this.name + " ]";
    }

    @Override
    public int hashCode() {
        return this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        Person p = (Person)obj;
        return this.id == p.id;
    }
}
{[ id = 330, name = TNT ]=3, [ id = 220, name = Jack ]=2, [ id = 110, name = Tom ]=4}

Process finished with exit code 0

TreeMap(注意下面代码中的泛型使用)

存储原理:基于红黑树的(二叉数)对键进行自然排序。

注意事项:1)向TreeMap添加元素时,如果元素的键具有自然顺序时,会按照自然顺序排序。

              2)-----------------------,-----------------不具有自然顺序,要实现Compareable接口。

     3)-----------------------,--------------------------------,没有实现-----------------,必须在创建TreeMap时,传入比较器。

import java.util.*;

public class ex12 {
    public static void main(String[] args) {
     TreeMap<Emp, Integer> map1 = new TreeMap<Emp, Integer>();
        map1.put(new Emp("Tom", 200), 100);
        map1.put(new Emp("Tom", 20), 200);
        map1.put(new Emp("Tom", 190), 300);
        map1.put(new Emp("Tom", 200), 400);
        System.out.println(map1);

        }
    }

class Emp implements Comparable<Emp>{
    String name;
    int salary;

    public Emp(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }

    @Override
    public int compareTo(Emp o) {
        return this.salary - o.salary;
    }

    @Override
    public String toString() {
        return "[ name = " + this.name + ", salary = " + this.salary + " ]";
    }
}
{[ name = Tom, salary = 20 ]=200, [ name = Tom, salary = 190 ]=300, [ name = Tom, salary = 200 ]=400}

Process finished with exit code 0
原文地址:https://www.cnblogs.com/lifehrx/p/5807356.html