劳资的Java也算是入了门了

本文深入解析Java集合框架,包括List、Set、Map等核心接口及其主要实现类如ArrayList、LinkedList、HashSet、TreeSet、HashMap的内部机制。探讨了数据结构如数组、链表、哈希表、红黑树的应用,并分析了各种集合类的特点与使用场景。

1.集合

1.1List

public interface Collection<E> extends Iterable<E> {}

这就意味着所有的实现集合类的接口都要可以迭代遍历~(tm废话)

boolean add(E e);该方法也就意味着Collection与Map无缘了(因为Map都是put方法呀..)

Collection下的主要子接口有List和Set,其中List的主要实现类有ArrayList,LinkedList和vetor(这他么是个啥)

ArrayList:顺序表、用数组实现、非线程安全
LinkedList:链表、双向链表实现、非线程安全

看一下ArrayList的默认构造方法:

public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

 这个elementData和DEFAULTCAPACITY_EMPTY_ELEMENTDATA是什么呢?

看一下定义:

transient Object[] elementData;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

emmmm,一个声明数组,一个负责塞一个空数组进去。

我一直在想ArrayList默认的大小是15还是16来着,构造方法里并木有给size这个属性赋值鸭...然后去看add方法,嗯,明白了

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private static final int DEFAULT_CAPACITY = 10;

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
      if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

这几行你们自己看吧,反正意思就是,你不往List里面放data,劳资是绝对不会设置size大小的

同时看一下这个代码

    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);
    }

grow方法应该就是传说中的额size大小不够情况下的size扩容了。里面有一些位操作符,所以看不太懂..我猜大概就是double+1的意思

最后一句使用的Arrays.copyOf方法是java.util包下面的一个工具类,看了一眼里面有好多sort、binarySearch、copyOf以及我测试的时候经常使用的toString方法,嗯,good class,需要好好看一下。

好,ArrayList说完了,开始我们的LinkedList,同样从构造方法看起

    public LinkedList() {
    }

你看这个构造方法就简单多了(emmmm)

那我们还是看一下他的成员变量吧

    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

嗯,很经典的Node结构,大学亲爱的王老师有在算法与数据结构课里讲过。

我们看一下他的add方法

    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

(这一行话时候来加的,这段linkLast的代码蛮有意思的,现在看能看懂了,当年大二的时候看的头都大了..而且所谓的双向链表就是在Node类里面定义两个指针吧,一个是previous,一个是next)

哦~这就很明显了嘛,每次new一个新Node,然后放在最后的位置,然后把size和modCount都++

又扫了一眼里面的方法,发现有pop和push方法哎

    public void push(E e) {
        addFirst(e);
    }

    public E pop() {
        return removeFirst();
    }

那就可以当栈或使用了,再配合着remove(last)使用,是不是又可以当队列使用了?但是Java好像有Queue的实现呀emmmm

我们看一下传说中链表的get方法

    Node<E> node(int arg0) {
		Node arg1;
		int arg2;
		if (arg0 < this.size >> 1) {
			arg1 = this.first;

			for (arg2 = 0; arg2 < arg0; ++arg2) {
				arg1 = arg1.next;
			}

			return arg1;
		} else {
			arg1 = this.last;

			for (arg2 = this.size - 1; arg2 > arg0; --arg2) {
				arg1 = arg1.prev;
			}

			return arg1;
		}
	}

看到没,每次都要遍历一下,时间复杂度是O(n),ArrayList的get的时间复杂度是O(1),啧啧....

set也是..

1.2 Set

Set: 元素无序、元素不可重复、没有索引
HashSet:哈希表实现
TreeSet: 红黑树实现

先从HashSet看起,照旧先看构造方法

    public HashSet() {
        map = new HashMap<>();
    }

emmm底层是HashMap,那算了,本来想具体看一下他的Hash值得算法,等到一会Map章节再看吧,那TreeSet底层想必也就是TreeMap喽~那就开始

2 Map

2.1 TreeMap

我对红黑树RBTree的理解有限,所以先参考了这篇文章:

红黑树-深入剖析及Java实现 - 美团技术团队的文章 - 知乎(很重要)

先看构造方法

    /**
     * Constructs a new, empty tree map, using the natural ordering of its
     * keys.  All keys inserted into the map must implement the {@link
     * Comparable} interface.  Furthermore, all such keys must be
     * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
     * a {@code ClassCastException} for any keys {@code k1} and
     * {@code k2} in the map.  If the user attempts to put a key into the
     * map that violates this constraint (for example, the user attempts to
     * put a string key into a map whose keys are integers), the
     * {@code put(Object key, Object value)} call will throw a
     * {@code ClassCastException}.
     */
    public TreeMap() {
        comparator = null;
    }

他这里直接将comparator置空了,comparator应该是成员变量的一个,我顺便把他所有的成员变量都贴上来吧

    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial
     */
    private final Comparator<? super K> comparator;

    private transient Entry<K,V> root;

    /**
     * The number of entries in the tree
     */
    private transient int size = 0;

    /**
     * The number of structural modifications to the tree.
     */
    private transient int modCount = 0;

然后看一眼喜闻乐见的put方法

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     *
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     * @throws ClassCastException if the specified key cannot be compared
     *         with the keys currently in the map
     * @throws NullPointerException if the specified key is null
     *         and this map uses natural ordering, or its comparator
     *         does not permit null keys
     */
    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }

其实增删方法就是普通的二叉查找树(Binary Search Tree)的方法,不过最后多做了一个修复的操作:fixAfterInsertion(e);

我们来感受一下这个红黑树的自平衡操作

调整函数fixAfterInsertion()的具体代码如下,其中用到了上文中提到的rotateLeft()和rotateRight()函数。通过代码我们能够看到,情况2其实是落在情况3内的。情况4~情况6跟前三种情况是对称的,因此图解中并没有画出后三种情况,读者可以参考代码自行理解。//此处及上图转自知乎

//红黑树调整函数fixAfterInsertion()
private void fixAfterInsertion(Entry<K,V> x) {
    x.color = RED;
    while (x != null && x != root && x.parent.color == RED) {
        if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
            Entry<K,V> y = rightOf(parentOf(parentOf(x)));
            if (colorOf(y) == RED) {//如果y为null,则视为BLACK
                setColor(parentOf(x), BLACK);              // 情况1
                setColor(y, BLACK);                        // 情况1
                setColor(parentOf(parentOf(x)), RED);      // 情况1
                x = parentOf(parentOf(x));                 // 情况1
            } else {
                if (x == rightOf(parentOf(x))) {
                    x = parentOf(x);                       // 情况2
                    rotateLeft(x);                         // 情况2
                }
                setColor(parentOf(x), BLACK);              // 情况3
                setColor(parentOf(parentOf(x)), RED);      // 情况3
                rotateRight(parentOf(parentOf(x)));        // 情况3
            }
        } else {
            Entry<K,V> y = leftOf(parentOf(parentOf(x)));
            if (colorOf(y) == RED) {
                setColor(parentOf(x), BLACK);              // 情况4
                setColor(y, BLACK);                        // 情况4
                setColor(parentOf(parentOf(x)), RED);      // 情况4
                x = parentOf(parentOf(x));                 // 情况4
            } else {
                if (x == leftOf(parentOf(x))) {
                    x = parentOf(x);                       // 情况5
                    rotateRight(x);                        // 情况5
                }
                setColor(parentOf(x), BLACK);              // 情况6
                setColor(parentOf(parentOf(x)), RED);      // 情况6
                rotateLeft(parentOf(parentOf(x)));         // 情况6
            }
        }
    }
    root.color = BLACK;
}

上面就是红黑树的自平衡规则被破坏后的修复工作。

对了还要说一点就是TreeMap的构造方法里面可以传一个Comparator类型的参数,当比较器用。如果构造器里面参数,那就使用默认的构造器。(其实一般情况下默认的构造器就已经够用了,除非你的业务有自己的需求)

2.2 HashMap

听说Java8把HashMap底层从数组转为链表了

先看Java8里面的成员变量和构造方法

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;


    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

默认大小DEFAULT_INITIAL_CAPACITY是16,注释里面的MUST be a power of two.意思是,容量是2的幂次方,因为底层是二叉查找树(红黑树)嘛,不然这个二叉树没法维护

还有这个1 << 4、1 << 16分别是2的4次方、2的16次方的意思,原理搜了一下大概是这个意思:

十进制1=二进制1,<<是位左移操作符,那么1 << 4,就是把二进制的1左移了4位,就变成了二进制的10000,就是十进制中的2的4次方,就是十进制的16啦~

然后继续看HashMap的put操作

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

这里计算Hash值的代码就一句话(h = key.hashCode()) ^ (h >>> 16),

其中^是异或运算符,>>>:按位右移补零操作符。左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充。

hashCode()方法在不同的Object类中应该都不一样,而Object类中默认hashCode()方法是这样子的

    public native int hashCode();

对的,是一个native方法,你是看不到滴。

那就不要纠结他了,直接看put方法吧

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        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) {
                    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;
    }

底层已经变成链表了。

2.2 LinkedHashMap

LinkedHashMap类是继承了HashMap类的,只是在父类基础上,增加了map之间的指针,所以遍历LinkedHashMap时顺序是与插入顺序相同的,而HashMap就做不到这一点。嗯!

3 Object类和String类

  • Object 类是类层次结构的 根类。每个类都使用 Object 作为超类。每个类,都直接或间接继承 Object 类
  • 我们所定义类,没有显示继承其他类,所有这些类在java语言中默认继承 Object 类,可以直接调用 Object 的成员方法
  • //转自知乎

下面这几行也是转自知乎的

3. getClass() 方法public final Class getClass()获取该对象所对应的类的字节码文件对象 , 也是返回该对象的运行时类的java.lang.Class对象JButton b1 = new JButton("button1");
System.out.println(b1.getClass());
//输出:
class javax.swing.JButton
4. hashCode() 方法public int hashCode()返回该对象的 哈希码值两个相等的对象,要求返回相等的 哈希码值static int hashCode(Object a) : 如果 a 为 null 返回 0,否则返回a.hashCode()5. finalize() 方法垃圾回收器准备释放内存的时候,会先调用 finalize()当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。(垃圾回收器的执行时机不确定)子类可以重写 finalize 方法,以配置系统资源或执行其他清除初衷:虽然,在jvm中,垃圾回收器,可以帮助我们自动回收垃圾(仅限于java产生的垃圾),但是对于本地方法,所使用的一些特殊的,jvm所管理不了的内存,这些释放特殊内存空间的代码,就放在 finalize注意:对象不一定会被回收。垃圾回收只与内存有关。垃圾回收和 finalize() 都是靠不住的,只要JVM 还没有快到耗尽内存的地步,它是不会浪费时间进行垃圾回收的
6. clone() 方法
protected Object clone()
创建并返回此对象的一个副本。
深复制和浅复制:
浅复制(浅克隆)
浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
深复制(深克隆)
深复制把要复制的对象所引用的对象都复制了一遍。
7. toString() 方法返回该对象的字符串表示。通常,toString 方法会返回一个 以文本方式表示 此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、标记符“@”和此对象哈希码的无符号十六进制表示组成。 换句话说,该方法返回一个字符串,它的值等于: getClass().getName() + '@' + Integer.toHexString(hashCode())

下面是关于String类的

二、String 类1. 概述字符串是由多个字符组成的一串数据(字符序列)字符串可以看成是字符数组String 类对象不能被修改2. 构造方法public String()
public String(byte[] bytes)
public String(byte[] bytes,int offset,int length)
public String(char[] value)
public String(char[] value,int offset,int count)
public String(String original)
3. String类的判断功能boolean equals(Object obj)    //两个字符串的内容是否相同
boolean equalsIgnoreCase(String str)   //两个字符串的是否相同的比较、(忽略字符串的大小写)
boolean contains(String str)  // 判断当前字符串中,是否包含指定字符
boolean startsWith(String str)   //判断当前字符串,是否是由指定字符串开头
boolean endsWith(String str)   //判断当前字符串,是否是由指定字符串结尾
boolean isEmpty()   //判断一个字符串是否是空串
4. String类的获取功能int length()    //获取当前字符串中的字符序列中,所包含的字符个数
char charAt(int index)     //获取字符串中指定位置的字符
int indexOf(int ch)  //返回指定字符,在字符数组位置

//查找指定字符串,在当前字符串中的位置
// 返回结果是指: 指定字符串中的第一个字符
// 在当前字符串中的位置(只匹配首次出现的单词)
// 如果返回-1,说明再这个字符串中没有与之匹配的
int indexOf(String str)

//从当前字符串指定位置fromIndex往后查找指定的字符ch或者字符串str
int indexOf(int ch,int fromIndex)
int indexOf(String str,int fromIndex)

//从 start 开始,截取到末尾
String substring(int start)
//从 start 开始,end 结束截取到末尾
String substring(int start,int end)

//比如:
String s = "说大放送发康师傅说卡卡卡啊说是";
String s1 = s.substring(2); // 放送发康师傅说卡卡卡啊说是
System.out.println(s1);
String s2 = s.substring(2, 4); //放送
System.out.println(s2);

 

 

 

待续....

 

//todo

java.util.Arrays类

transient 关键字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值