Java collection 01_ArrayList, LinkedList and Vector

Java collection

Advantages of arrays:

The elements allocate space continuously, and access the elements according to the subscript (high random access efficiency)

Limitations of arrays:

The length is fixed and cannot be automatically expanded

Delete and insert operations are inefficient and need to move a large number of elements

The type of element can only be one

The elements allocate space continuously, and a continuous memory space must be found in the heap memory to store the array (higher memory requirements)


In order to solve the limitations of arrays, the concept of container classes is introduced

Insert picture description here

ArrayList

The underlying data structure of ArrayList is an array, which is fast in query, slow in adding and deleting, unsafe threads, and high efficiency

add()size()isEmpty()
contains()indexOf()lastIndexOf()
iterator()remove()set()
get()toArray()clear()
public static void main(String[] args) {
    
    

	ArrayList<String> arrayList = new ArrayList<String>();
	arrayList.add("hello");
	arrayList.add("world");
	arrayList.add("BLU");
	arrayList.add("everyday");
	arrayList.add(3,"happy");
	
	System.out.println(arrayList);
	System.out.println("size:"+arrayList.size());
	System.out.println("是否为空集合:"+arrayList.isEmpty());
	System.out.println("位置为3的元素:"+arrayList.get(3));
	System.out.println("是否包含元素'BLU':"+arrayList.contains("BLU"));
	System.out.println("元素'BLU'所在位置:"+arrayList.indexOf("BLU"));
	System.out.println("元素'BLU'最后出现的位置:"+arrayList.lastIndexOf("BLU"));
	
	Iterator it = arrayList.iterator();
	while(it.hasNext()) {
    
    
		String s1 = (String) it.next();
		System.out.println("迭代器迭代:"+s1);
	}
	
	arrayList.remove("BLU");
	arrayList.remove(1);
	arrayList.set(0, "HELLO!");
	
	for(int i=0; i<arrayList.size();i++) {
    
    
		String s2 = (String) arrayList.get(i);
		System.out.println("for循环输出:"+s2);
	}

	for(String s : arrayList) {
    
    
		System.out.println("增强for循环输出:"+s);
	}
	
	Object[] array = arrayList.toArray();
	
	for (int i = 0; i < array.length; i++) {
    
    
		System.out.println("数组:"+array[i]);
	}
	
	arrayList.clear();
	System.out.println("size:"+arrayList.size());
	
}
[hello, world, BLU, happy, everyday]
size:5
是否为空集合:false
位置为3的元素:happy
是否包含元素'BLU':true
元素'BLU'所在位置:2
元素'BLU'最后出现的位置:2
迭代器迭代:hello
迭代器迭代:world
迭代器迭代:BLU
迭代器迭代:happy
迭代器迭代:everyday
for循环输出:HELLO!
for循环输出:happy
for循环输出:everyday
增强for循环输出:HELLO!
增强for循环输出:happy
增强for循环输出:everyday
数组:HELLO!
数组:happy
数组:everyday
size:0
containsAll()	本集合是否包含指定集合中的所有元素
addAll()		将指定集合中的所有元素添加到本集合
removeAll()		移除本集合中与指定集合的交集部分
retainAll()		移除本集合中指定集合的补集部分,保留交集
public static void main(String[] args) {
    
    

	ArrayList<String> arrayList1 = new ArrayList<String>();
	arrayList1.add("aaa");
	arrayList1.add("bbb");
	arrayList1.add("ccc");
	ArrayList<String> arrayList2 = new ArrayList<String>();
	arrayList2.add("ccc");
	arrayList2.add("ddd");
	arrayList2.add("eee");
	
	System.out.println("list1:"+arrayList1);
	System.out.println("list2:"+arrayList2);
	System.out.println("list1是否包含list2中的所有元素:"+arrayList1.containsAll(arrayList2));
	arrayList1.addAll(arrayList2);
	System.out.println("list1:"+arrayList1);
	arrayList1.removeAll(arrayList2);
	System.out.println("list1:"+arrayList1);
	arrayList1.add("ccc");
	arrayList1.retainAll(arrayList2);
	System.out.println("list1:"+arrayList1);

}
list1:[aaa, bbb, ccc]
list2:[ccc, ddd, eee]
list1是否包含list2中的所有元素:false
list1:[aaa, bbb, ccc, ccc, ddd, eee]
list1:[aaa, bbb]
list1:[ccc]

The length of the array is limited, and the ArrayList can store any number of objects, the length is not limited, how is it achieved?

Use array expansion method!

The default initial capacity size of ArrayList is DEFAULT_CAPACITY = 10

When add() finds that the required capacity minCapacity exceeds the initial capacity, it will enter the grow(int minCapacity) method to expand, create a new ArrayList with a capacity 1.5 times the old capacity, and copy the original array data to the new array

int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);

Note: The common way of writing will declare the reference as the interface List type

写法一:
ArrayList<String> h=new ArrayList<String>();

写法二(推荐):
List<String> mylist = new ArrayList<String>();
写法一用当前类作为引用类型,那么可以访问到ArrayList这个类中的所有公用方法。
写法二用接口List作为引用类型,那么通过list引用可以访问到接口中定义的方法。但是就无法调用的List接口以外的方法了。

设计模式中有:“代码尽量依赖于抽象,不依赖于具体”。
第一种形式就是依赖具体,第二种形式就是依赖于抽象。
代码依赖于抽象的好处是,代码可以方便替换。

例如,代码List list = new ArrayList();下面通过list来操作集合。
代码编写后发现集合使用的不准确,应该使用LinkedList,那么只要修改一行代码List list = new LinkedList();就可以了
因为List接口保证了调用的都是接口中的方法,而ArrayList与LinkedList都实现了List接口。
而如果当时用ArrayList list = new ArrayList()这种形式的话,那么list访问到的就可能是ArrayList里独有的方法而非List接口中的方法。
这样替换成LinkedList的时候就有可能需要修改很多的代码。

LinkedList

LinkedList: The underlying data structure is a linked list, which is slow in query, fast in addition and deletion, unsafe threads, and high efficiency

LinkedList, like ArrayList, implements the list interface and also has related methods of the list interface

In addition, LinkedList also implements the Deque interface, so it also has the following unique methods:

addFirst()addLast()
offerFirst()offerLast()
getFirst()getLast()
removeFirst()removeLast()

addFirst()offerFirst() 的区别是前者返回void,后者固定返回true
public static void main(String[] args) {
    
    
	LinkedList<String> list = new LinkedList<String>();
	list.add("hello");
	list.add("world");
	list.addFirst("Hi");
	list.addLast("BLU!");
	System.out.println(list);
	
	Iterator<String> it = list.iterator();
	while(it.hasNext()) {
    
    
		System.out.println(it.next());
	}
	
	System.out.println("头部元素:"+list.getFirst());
	System.out.println("尾部元素:"+list.getLast());
	list.removeFirst();
	list.removeLast();
	list.offerFirst("first");
	list.offerLast("last");
	System.out.println(list);
}
[Hi, hello, world, BLU!]
Hi
hello
world
BLU!
头部元素:Hi
尾部元素:BLU!
[first, hello, world, last]

The difference between ArrayList and LinkedList:

The bottom layer of ArrayList is an array, and LinkedList is a data structure based on a linked list

ArrayList query is fast, while LinkedList query needs to move the pointer, which is inefficient

For adding and deleting operations, LinkedList is dominant, while adding and deleting ArrayList requires moving data, which is inefficient


Vector

Vector: The underlying data structure is an array, fast query, slow addition and deletion, thread safety, low efficiency

public static void main(String[] args) {
    
    

	Vector<String> list = new Vector<String>();
	list.addElement("hello");
	list.addElement("world");
	list.addElement("BLU");
	
	for(int i=0;i<list.size();i++) {
    
    
		System.out.println(list.elementAt(i));
	}
	
	Enumeration<String> elements = list.elements();
	
	while(elements.hasMoreElements()) {
    
    
		System.out.println(elements.nextElement());
	}
}
hello
world
BLU
hello
world
BLU

Case 1: Remove duplicate values ​​of strings in the collection

思路1:创建一个新集合,遍历原集合,元素依次存入新集合,存入之前判断在新集合中是否已经存在
思路2:依次比较集合中的元素和集合后面的所有元素,发现有相同的值就把后面的元素删掉

Idea 1 (note this contains() method, its bottom layer is equals() method, if it is a normal object, the equals method in the parent class Object is called, and the equals method in Object judges whether the address value is Same, so this ordinary object needs to override the equals method):

public static void main(String[] args) {
    
    
	ArrayList<String> list = new ArrayList<>();
	list.add("a");
	list.add("b");
	list.add("c");
	list.add("d");
	list.add("c");
	list.add("c");
	list.add("e");
	list.add("b");
	ArrayList<String> newlist = new ArrayList<>();
	
	for(int i=0;i<list.size();i++) {
    
    
		if(!newlist.contains(list.get(i))) {
    
    
			newlist.add(list.get(i));
		}
	}
		
	System.out.println(newlist);
}
[a, b, c, d, e]

Idea 2 (note that y is subtracted, because after deleting an element, the index of subsequent elements will change):

public static void main(String[] args) {
    
    
	ArrayList<String> list = new ArrayList<>();
	list.add("a");
	list.add("b");
	list.add("c");
	list.add("d");
	list.add("c");
	list.add("c");
	list.add("e");
	list.add("b");
	
	for(int i=0;i<list.size()-1;i++) {
    
    
		for(int j=i+1;j<list.size();j++) {
    
    
			if(list.get(i).equals(list.get(j))) {
    
    
				list.remove(j);
				j--;
			}
		}
	}
	
	System.out.println(list);	
		
}
[a, b, c, d, e]

Guess you like

Origin blog.csdn.net/BLU_111/article/details/108343047