J2EE
目录
4、查找,代码应该也都能看懂了,不做注释了,如有需求,就加上。
一、特点
以键值对的形式对元素进行存储,底层结构为哈希表(数组+链表+红黑树)。键唯一且可以为空。
二、使用
1、增加
首先我们要搞清楚Set和Map的存储元素过程的区别。
Set集合是没有键的,如果没有重写hashCode方法,那么添加的元素的哈希值就是通过元素的内存地址计算得
出,如果重写了hashCode方法,这是根据重写的hashCode方法计算出的hash值然后计算出table数组下标,再一
个个进行equals比较元素是否为同一个元素。重写了equals方法一定要重写hashCode方法原因不再过多解释了。
HashSet的add方法就是调用了HashMap的put方法,这里没有键的概念,就是将add进来的元素当做键来存储。
我们来看一下Set集合添加方法的源码:
//实例HashSet
HashSet<String> s=new HashSet<String>();
s.add("a");
//add()源码
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
//在理解map.put()方法前先来理解HashMap中的一个内部类Node。我们添加进来的每一个元素就是每一个Node(K,V)
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
//该属性可以先下面图解
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
/**
* 返回该Node对象的哈希值
**/
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
/**
*修改Node对象的value值
**/
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
/**
*判断两个Node对象是否相等,相等返回true
**/
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
图解:
其实哈希表结构中的链表也可以按照这个图解来理解。
接下来理解map.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;
//如果table数字还未初始化
if ((tab = table) == null || (n = tab.length) == 0)
//初始化table数组
n = (tab = resize()).length;
//(n - 1) & hash:通过这个运算计算出对应的下标
//如果数组中该位置没有元素
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) {
//e指向下一个Node对象来实现不断往下比较
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;
}
Map集合是键值对形式,根据键值计算出哈希值后得出table数组下标,然后先判断是否有重复的键,有则用新
value覆盖原value。不同元素计算出来的哈希值肯定不同,但是计算出的table数组的下标可能相同,这是去重原
理中的一个流程。
2、删除
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//如果tab[index]和存储的元素键值相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//指针指向node
node = p;
//否则e = p.next e的指针指向下一个node
else if ((e = p.next) != null) {
//如果是红黑树
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
//如果是链表,不停往下寻找键相同的node
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<K,V>)node).removeTreeNode(this, tab, movable);
//如果这个tab[index]下面没有元素会出现node == p 的情况
else if (node == p)
//那么tab[index]会被移除,tab[index] = node.next;node.next是为null的
tab[index] = node.next;
else
//说明下面存在链表结构 改变node元素中next属性的指标指向node的下一个
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
3、修改
//源码
@Override
public V replace(K key, V value) {
Node<K,V> e;
//在哈希表结构中或者键值为key的node
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
//新value替换旧value
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
4、查找,代码应该也都能看懂了,不做注释了,如有需求,就加上。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> 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<K,V>)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;
}
5、遍历
//方法一:获得底层结构元素中的所有的key值,然后进行遍历
Set<String> keys = m.keySet();
for (String s : keys) {
System.out.println(m.get(s));
}
//这里会不断的调用m.get()方法,性能可想是会有影响的
//方法二:获得所有的Node进行forEach遍历,性能比方法一好
Set<Entry<String, Integer>> e = m.entrySet();
for (Entry<String, Integer> entry : e) {
System.out.println(entry.getKey()+"--"+entry.getValue());
}
二、泛型
1、作用:
①运行时产生的异常转换为编译期的错误
②提高代码健壮性
代码:
package com.zwf.collection;
public class Test {
public static void main(String[] args) {
//实例化普通类s,泛型类s2
S s=new S();
S2<String> s2=new S2<String>();
//String-->Integer肯定会报错 泛型类将将运行时会报的错转换成编译会报的错
Integer n=(Integer) s.getA();
//Integer n2=(Integer) s2.getA();改行编译会报错
//在S2中定义增删改一些方法,泛型指定为什么就是添加什么,可以定义通用的增删改
new S2<String>().add("");
}
}
/**
* 泛型类
* @author zjjt
*
* @param <T>
*/
class S2<T> {
T a;
public T getA() {
return a;
}
public void setA(T a) {
this.a = a;
}
public S2() {
// TODO Auto-generated constructor stub
}
public S2(T a) {
super();
this.a = a;
}
@Override
public String toString() {
return "MyInteger [a=" + a + "]";
}
public T add(T d) {
return d;
}
}
/**
* 普通类
* @author zjjt
*
*/
class S{
Object a;
public Object getA() {
return a;
}
public void setA(Object a) {
this.a = a;
}
public S(Object a) {
super();
this.a = a;
}
@Override
public String toString() {
return "Integer [a=" + a + "]";
}
public S() {
// TODO Auto-generated constructor stub
}
}
三、框架集合工具类
1、Collections.sort(m);
Arrays.toString()
list.toArray()
package com.zwf.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.catalina.ha.backend.CollectedInfo;
public class Test {
public static void main(String[] args) {
List<String> m=new ArrayList();
m.add("b");
m.add("a");
m.add("f");
m.add("d");
//排序
Collections.sort(m);
System.out.println(m);
//集合转数组,数组打印的是地址,使用Arrays.toString()可以打印出内容
Object[] a = m.toArray();
System.out.println(Arrays.toString(a));
//数组转集合 但是不能违背数组本质。集合的api要比数据丰富,提供了更多处理方法
List<Object> aL = Arrays.asList(a);
}
}
aL集合的更多处理方法