values()方法:看下面的实例,就是把所有的value值封装成一个connection型的数组
Mapstudents=new HashMap<>(); students.put(1, new Student("111")); students.put(2, new Student("111")); Collection stuValues = students.values(); for (Object stuValue : stuValues) { System.out.println(stuValue); }
输出结果
com.xt.map.Student@52e922
com.xt.map.Student@25154f
remove()方法
final NoderemoveNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node [] tab; Node p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) { if (p instanceof TreeNode) node = ((TreeNode )p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode )node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }
看上面的红色代码,这个事底层代码,就是判定remove的是谁,,,怎么去判断的依据,下面就是依据
1:判定HashCode值是否相同 e.hash == hash
2:判定地址是否相同 k = e.key) == key
3:equals方法 key.equals(k))
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
如果为真就删除了这个对象
containsKey()方法
*/ final NodegetNode(int hash, Object key) { Node [] tab; Node first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode )first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
我们发现红色的字体和remove方法道理相同,这里就不过多解释了
containsValues()方法
public boolean containsValue(Object value) { Node[] tab; V v; if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) { for (Node e = tab[i]; e != null; e = e.next) { if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; }
(v = e.value) == value || (value != null && value.equals(v))
这个意思就是:如果value地址相同,或者本身的值相同,然后equals方法
如果是基本类型:例如2==2 直接就为TRUE
如果是引用类型:new Student(111)==new Student(222) 为FALSE 但是value.equals(v)为真 最后还是返回TRUE
OK~