ArrayList和HashSet的增删操作区别

一, List和Set


	public static void main(String[] args) {
		test1();
	}

     public static void test1() {
		List<Integer> list = new ArrayList<>();
		Set<Integer> set = new HashSet<>();
		for (int i = -3; i < 3; i++) {
			list.add(i);
			set.add(i); 
		}
		for (int i = 0; i < 3; i++) {
			list.remove(i);
			set.remove(i);
		}
		System.out.println(list + " " + set);
	}

结果打印:

[-2, 0, 2] [-1, -2, -3]

1, 新增操作add()代码分析

1.1   ArrayList


    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

ArrayList新增逻辑是将元素按照先后顺序依次存进数组中, 所以test1()的循环中list.add(i)的运行结果是:

[-3] --> [-3, -2] --> [-3, -2, -1] --> [-3, -2, -1, 0] --> [-3, -2, -1, 0, 1, 2]

List新增操作, 对应的元素有序可重复

1.2  HashSet


    private transient HashMap<E,Object> map;

/**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

HashSet新增逻辑是将元素以map的形式存进hash表中,  test1()的循环中set.add(i)的运行结果是:

[-3] --> [-2, -3] --> [-1, -2, -3] --> [-1, 0, -2, -3] --> [-1, 0, -2, 1, -3, 2]

Set新增操作, 对应的元素无序不可重复(出现重复时, 新元素会覆盖掉对应旧的元素)

2, 删除操作remove()代码分析

1.1   ArrayList

public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }


public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

ArrayList的删除操作有两种实现方式: 

扫描二维码关注公众号,回复: 4533003 查看本文章

remove(int index) : 按元素下标位置进行删除

remove(Object o) :  直接按照元素的value值进行匹配删除

此处, test1()的循环中list.remove(i)调用的是remove(int index)方法, 所以代码list.remove(i)运行结果是:

[-3, -2, -1, 0, 1, 2] --> [-2, -1, 0, 1, 2] --> [-2, 0, 1, 2] --> [-2, 0, 2],   依次删除了元素-3, -1, 1

1.2  HashSet

 /**
     * Removes the specified element from this set if it is present.
     * More formally, removes an element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
     * if this set contains such an element.  Returns <tt>true</tt> if
     * this set contained the element (or equivalently, if this set
     * changed as a result of the call).  (This set will not contain the
     * element once the call returns.)
     *
     * @param o object to be removed from this set, if present
     * @return <tt>true</tt> if the set contained the specified element
     */
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

HashSet的删除操作就一种实现方式: 

remove(Object o) : 直接按照元素的value值进行匹配删除

此处, test1()的循环中set.remove(i)调用的是remove(Object o)方法, 所以代码set.remove(i)运行结果是:

[-1, 0, -2, 1, -3, 2] --> [-1, -2, 1, -3, 2] --> [-1, -2, -3, 2] --> [-1, -2, -3], 依次删除了元素0, 1, 2

猜你喜欢

转载自blog.csdn.net/weixin_39039342/article/details/84761295