集合

一、集合基础
1、List有序可重复ArrayList,Vector, LinkedList。继承Comparable类重写compareTo方法。
ArrayList 和Vector 都是使用数组方式存储数据,读快改慢。ArrayList线程不安全,一半增长;Vector线程安全,一倍增长。
LinkedList 使用双向链表实现存储,读慢改快。
2、Set无序不重复。set中保存对象时重写equals、hashCode方法保证不重复。重写hashCode保证“两个对象相等,那么它们的hashCode()值一定相同”。

实现有序不重复:
     1)循环排除重复,添加时使用contains判断;
     2)使用TreeSet,new TreeSet(arlList)。
3、Collection与Collections的区别
Collection 是一个集合接口,拥有list、set两个类型。
Collections是一个包装类,不能实例化。它包含有各种有关集合操作的静态多态方法。sort/max/min/copy。

如:Collections.sort(list);
二、遍历
List
1、超级for循环遍历
for(String attribute : list) {
  System.out.println(attribute);
}
2、索引遍历
for(int i = 0 ; i < list.size() ; i++) {
  system.out.println(list.get(i));
}
3、Iterator遍历
for(Iterator it = exampleList.iterator();it.hasNext();){
    system.out.println(it.next());
}
Set
1、超级for循环
for (String str : set) {
      System.out.println(str);
}
2、Iterator遍历
for(Iterator it2 = set.iterator();it2.hasNext();){
   System.out.println(it2.next());
}
Map
1、entrySet
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { 
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}
2、keySet
for (Integer key : map.keySet()) { 
  System.out.println("Key = " + key+";value="+map.get(key)); 

3、Iterator+entrySet
for(Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); it.hasNext();){
    Map.Entry<Integer, Integer> entry = it.next(); 
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
}
4、Iterator+keySet
for(Iterator<Integer> it = map.keySet().iterator(); it.hasNext();){
    Integer key = it.next(); 
    System.out.println("Key = " + key+";value="+map.get(key)); 
}
三、源码解析
1、ArrayList扩容分析,当调用add方法时首先判断是否需要扩容,如果需要就newCapacity = oldCapacity + (oldCapacity >> 1)作为新的size调用Arrays.copyOf新建一个数组。
   private transient Object[] elementData;
   private int size;
   public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);  //size + 1
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);

    }
        //扩容
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));

        return copy;
    }
2、HashMap的工作原理
HashMap由数组+链表组成的,数组和链表的节点是一个Entry对象,Entry是Hashmap的内部类包含key、value、hash及下一个Entry。hash是通过调用hash方法计算hashCode的值使其均匀的分布到数组中。
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认加载因子
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
    transient int size;
    //内部类
         static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

     .......
    }
3、HashMap的put()方法的工作原理
    public V put(K key, V value) {
         //当key为null,调用putForNullKey方法,保存null于table第一个位置中
        if (key == null)
            return putForNullKey(value);
        //计算hash的值
        int hash = hash(key);
        //计算hash在数组的位置
        int i = indexFor(hash, table.length);
        //找到第i个元素迭代链表,如果key值相等就修改它的值
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        //没有相等的就在第i个元素的链表前面新加一个元素
        addEntry(hash, key, value, i);
        return null;
    }
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        h ^= k.hashCode();
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    static int indexFor(int h, int length) {
        //计算数组位置
        return h & (length-1);
    }
     void addEntry(int hash, K key, V value, int bucketIndex) {
                 //以2的倍数给数组扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
    扩容问题:随着HashMap中元素的数量越来越多,发生碰撞的概率就越来越大,所产生的链表长度就会越来越长,这样势必会影响HashMap的速度,为了保证HashMap的效率,系统必须要在某个临界点进行扩容处理。该临界点在当HashMap中元素的数量等于table数组长度*加载因子。但是扩容是一个非常耗时的过程,因为它需要重新计算这些数据在新table数组中的位置并进行复制处理。
    table长度是2的n次方:在indexFor方法中保证length-1的二进制是1111。只有这样的值按位与的时候才不会有一位永远是0导致内存浪费。h& (length-1)运算从数值上来讲其实等价于对length取模,也就是h%length。
        

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值