java中的Map

Maps:
HashMap
TreeMap,
LinkedHashMap,
WeakHashMap,
ConcurrentHashMap,
IdentityHashMap.
区别表现在
efficiency
the order in which the pairs are held and presented
how long the objects are held by the map
how the map works in multithreaded programs
how key equality is determined.

性能

HashMap使用了特殊的值,叫做散列码
hashCode()是根类Object中的方法,所有的java对象都能产生散列码
在这里插入图片描述

//: containers/Maps.java
// Things you can do with Maps.
import java.util.concurrent.*;
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class Maps {
  public static void printKeys(Map<Integer,String> map) {
    printnb("Size = " + map.size() + ", ");
    printnb("Keys: ");
    print(map.keySet()); // Produce a Set of the keys
  }
  public static void test(Map<Integer,String> map) {
    print(map.getClass().getSimpleName());
    map.putAll(new CountingMapData(25)); 					 /***输出所有的键值对*****/
    // Map has ‘Set’ behavior for keys:
    map.putAll(new CountingMapData(25));
    printKeys(map);
    // Producing a Collection of the values:
    printnb("Values: ");
    print(map.values());
    print(map);
    print("map.containsKey(11): " + map.containsKey(11));	/***是否包含key*****/
    print("map.get(11): " + map.get(11));					/***key所对应的value****/
    print("map.containsValue(\"F0\"): "
      + map.containsValue("F0"));							/***是否包含某个value*****/
    Integer key = map.keySet().iterator().next();			/***keySet可以返回所有的key值*****/
    print("First key in map: " + key);
    map.remove(key);										/***删除key***/
    printKeys(map);
    map.clear();
    print("map.isEmpty(): " + map.isEmpty());
    map.putAll(new CountingMapData(25));
    // Operations on the Set change the Map:
    map.keySet().removeAll(map.keySet());					/***删除所有的键值对*****/
    print("map.isEmpty(): " + map.isEmpty());
  }
  public static void main(String[] args) {
    test(new HashMap<Integer,String>());
    test(new TreeMap<Integer,String>());
    test(new LinkedHashMap<Integer,String>());
    test(new IdentityHashMap<Integer,String>());
    test(new ConcurrentHashMap<Integer,String>());
    test(new WeakHashMap<Integer,String>());
  }
} /* Output:
HashMap
Size = 25, Keys: [15, 8, 23, 16, 7, 22, 9, 21, 6, 1, 14, 24, 4, 19, 11,
18, 3, 12, 17, 2, 13, 20, 10, 5, 0]
Values: [P0, I0, X0, Q0, H0, W0, J0, V0, G0, B0, O0, Y0, E0, T0, L0, S0,
D0, M0, R0, C0, N0, U0, K0, F0, A0]
{15=P0, 8=I0, 23=X0, 16=Q0, 7=H0, 22=W0, 9=J0, 21=V0, 6=G0, 1=B0, 14=O0,
24=Y0, 4=E0, 19=T0, 11=L0, 18=S0, 3=D0, 12=M0, 17=R0, 2=C0, 13=N0,
20=U0, 10=K0, 5=F0, 0=A0}
map.containsKey(11): true
map.get(11): L0
map.containsValue("F0"): true
First key in map: 15
Size = 24, Keys: [8, 23, 16, 7, 22, 9, 21, 6, 1, 14, 24, 4, 19, 11, 18,
3, 12, 17, 2, 13, 20, 10, 5, 0]
map.isEmpty(): true
map.isEmpty(): true
...
*///:~

sortedMap

在这里插入图片描述
Comparator comparator( ): Produces the comparator used for this Map, or null for natural ordering.
T firstKey( ): Produces the lowest key.
T lastKey( ): Produces the highest key.
SortedMap subMap(fromKey, toKey): Produces a view of this Map with keys from fromKey, inclusive, to toKey, exclusive.
SortedMap headMap(toKey): Produces a view of this Map with keys less than toKey.
SortedMap tailMap(fromKey): Produces a view of this Map with keys greater than or equal to fromKey.

//: containers/SortedMapDemo.java
// What you can do with a TreeMap.
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class SortedMapDemo {
  public static void main(String[] args) {
    TreeMap<Integer,String> sortedMap =
      new TreeMap<Integer,String>(new CountingMapData(10));
    print(sortedMap);
    Integer low = sortedMap.firstKey();
    Integer high = sortedMap.lastKey();
    print(low);
    print(high);
    Iterator<Integer> it = sortedMap.keySet().iterator();
    for(int i = 0; i <= 6; i++) {
        if(i == 3) low = it.next();
        if(i == 6) high = it.next();
    	else it.next();
    }
    print(low);
    print(high);
    print(sortedMap.subMap(low, high));
    print(sortedMap.headMap(high));
    print(sortedMap.tailMap(low));
  }
} /* Output:
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0}
0
9
3
7
{3=D0, 4=E0, 5=F0, 6=G0}
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0}
{3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0}
*///:~

LinkedHashMap

在这里插入图片描述

//: containers/LinkedHashMapDemo.java
// What you can do with a LinkedHashMap.
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class LinkedHashMapDemo {
  public static void main(String[] args) {
    LinkedHashMap<Integer,String> linkedMap =
      new LinkedHashMap<Integer,String>(
        new CountingMapData(9));
    print(linkedMap);
    // 最小使用的次数
    linkedMap =
      new LinkedHashMap<Integer,String>(16, 0.75f, true);  //不知道这里怎么弄出来的
    linkedMap.putAll(new CountingMapData(9));
    print(linkedMap);
    for(int i = 0; i < 6; i++) //对前面六个元素进行访问
      linkedMap.get(i);
    print(linkedMap);//这里0~5就被挪到数组的后面去了
    linkedMap.get(0);//再访问一下0
    print(linkedMap);//0又被挪到数组的末尾去了
  }
} /* Output:
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0}
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0}
{6=G0, 7=H0, 8=I0, 0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0}
{6=G0, 7=H0, 8=I0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 0=A0}
*///:~

Hashing and hash code

这里有个bruce版超长代码来说明

  • 如果是自己的类,继承于基类object,生成散列码的时候就会使用object的hashCode方法生成散列码,而它默认是使用对象的地址计算散列码的
    所以要写hashCode的覆盖版本
  • HashMap使用equals判断当前的键是否与表中存在的键相同
    所以也要override equals()方法

在这里插入图片描述

这里是很(lan)详(de)细(kan)的代码

//: containers/Groundhog.java
    // Looks plausible, but doesn’t work as a HashMap key.
    public class Groundhog {
      protected int number;
      public Groundhog(int n) { number = n; }
      public String toString() {
        return "Groundhog #" + number;
      }
} ///:~
    //: containers/Prediction.java
    // Predicting the weather with groundhogs.
    import java.util.*;
    public class Prediction {
      private static Random rand = new Random(47);
      private boolean shadow = rand.nextDouble() > 0.5;
      public String toString() {
        if(shadow)
          return "Six more weeks of Winter!";
        else
          return "Early Spring!";
}
} ///:~
    //: containers/SpringDetector.java
    // What will the weather be?
    import java.lang.reflect.*;
    import java.util.*;
    import static net.mindview.util.Print.*;
    public class SpringDetector {
      // Uses a Groundhog or class derived from Groundhog:
      public static <T extends Groundhog>
      void detectSpring(Class<T> type) throws Exception {
        Constructor<T> ghog = type.getConstructor(int.class);
        Map<Groundhog,Prediction> map =
          new HashMap<Groundhog,Prediction>();
        for(int i = 0; i < 10; i++)
          map.put(ghog.newInstance(i), new Prediction());
        print("map = " + map);
        Groundhog gh = ghog.newInstance(3);
        print("Looking up prediction for " + gh);
        if(map.containsKey(gh))
          print(map.get(gh));
        else
          print("Key not found: " + gh);
      }
      public static void main(String[] args) throws Exception {
        detectSpring(Groundhog.class);
         }
} /* Output:
map = {Groundhog #3=Early Spring!, Groundhog #7=Early Spring!, Groundhog
#5=Early Spring!, Groundhog #9=Six more weeks of Winter!, Groundhog
#8=Six more weeks of Winter!, Groundhog #0=Six more weeks of Winter!,
Groundhog #6=Early Spring!, Groundhog #4=Six more weeks of Winter!,
Groundhog #1=Six more weeks of Winter!, Groundhog #2=Early Spring!}
Looking up prediction for Groundhog #3
Key not found: Groundhog #3
*///:~
// A class that’s used as a key in a HashMap
// must override hashCode() and equals().
public class Groundhog2 extends Groundhog {
  public Groundhog2(int n) { super(n); }
  public int hashCode() { return number; }
  public boolean equals(Object o) {
    return o instanceof Groundhog2 &&
      (number == ((Groundhog2)o).number);
}
} ///:~
//: containers/SpringDetector2.java
// A working key.
public class SpringDetector2 {
  public static void main(String[] args) throws Exception {
    SpringDetector.detectSpring(Groundhog2.class);
  }
} /* Output:
map = {Groundhog #2=Early Spring!, Groundhog #4=Six more weeks of
Winter!, Groundhog #9=Six more weeks of Winter!, Groundhog #8=Six more
weeks of Winter!, Groundhog #6=Early Spring!, Groundhog #1=Six more
weeks of Winter!, Groundhog #3=Early Spring!, Groundhog #7=Early
Spring!, Groundhog #5=Early Spring!, Groundhog #0=Six more weeks of
Winter!}
Looking up prediction for Groundhog #3
Early Spring!
*///:~

反正我觉得重点就这一点点
在这里插入图片描述
还有这一点点
在这里插入图片描述
hashingCode其实就是唯一表示key的东西,类似于id嘛

理解hashCode()

–这里是被省略的超长代码containers/SlowMap.java–
在这里插入图片描述
在这里插入图片描述
–被省略的container/MapEntry.java–
在这里插入图片描述
(不听不听?bruce念经)
(等我需要自己定义的时候再仔细看…)

为速度而散列

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

覆盖hashCode()

在这里插入图片描述
在这里插入图片描述
关于如何生成散列码
在这里插入图片描述
(哈这一节终于完了!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值