Java Basics - Complete Solution to ArrayList Method (Dictionary Version)

introduction

When using collections ArrayList, we often use add, removeetc., and there are many others that we have never used or even heard of. Now in this tutorial, we will briefly understand it, and it is not required to write down everything. It is equivalent to keeping it in your head. Building an index means not reinventing the wheel repeatedly when using certain methods.
Okay, okay.jpg

The ArrayList structure is as follows

image.png
Including the constructor method, there is 33a method in total.

start

The following methods are listed in no particular order

ArrayList()

You can use to new ArrayList()create a ArrayListcollection, as follows:

/**
 * 1 简单的ArrayList
 */
public static ArrayList getArrayList(){
    
    
    ArrayList arrayList = new ArrayList();
    arrayList.add("张三");
    arrayList.add("里斯");
    return arrayList;
}

Some editors will report a yellow line or light yellow background prompt, as shown below

Picture 1-1
This needs to be given ArrayLista type, for example ArrayList<String>.

ArrayList(Collection<? extends E> c)

You can put a collection into it for initialization ArrayList. The sample code is as follows:

HashSet<String> temp1 = new HashSet<>();
temp1.add("张三");
temp1.add("里斯");
ArrayList<String> arrayList2 = new ArrayList<>(temp1);
arrayList2.forEach(System.out::println);

ArrayList(int initialCapacity)

Construct an empty list with a specified initial capacity. The application scenario is when you roughly know the amount of data stored in this collection and directly define the capacity 避开集合自增空间浪费资源.

ArrayList<String> arrayList3 = new ArrayList<>(1000);

add() 与 add(int, E)

add()The method is to add the value in the brackets to the end of the set.
add(int, E)The data is inserted at the specific subscript, and the following table starts from zero.

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("张三");
arrayList.add(0,"在天");
arrayList.add("里斯");
arrayList.forEach(System.out::println);

addAll(Collection<? extends E> c)

指集合中的所有元素Append to the end of this list;

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("张三");
arrayList.add("李四");
arrayList.add("王二");
ArrayList<String> arrayList2 = new ArrayList<>();
arrayList2.add("麻子");
arrayList2.add("铁子");
arrayList.addAll(arrayList2);
System.out.println(arrayList);

Output:

[Zhang San, Li Si, Wang Er, Mazi, Tiezi]

addAll(int index,Collection<? extends E> c)

It is equivalent to the combined version of add(int index,E)and at the specified index subscript, and appends all the elements in the specified collection in sequence. For example, in the previous example, I want to insert both and into the queue later , so I can implement it as follows.addAll(Collection<? extends E> c)
张三麻子铁子

public static void testAddAllByIndex(){
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    ArrayList<String> arrayList2 = new ArrayList<>();
    arrayList2.add("麻子");
    arrayList2.add("铁子");
    arrayList.addAll(1,arrayList2);
    System.out.println(arrayList);
}

Output:

[Zhang San, Mazi, Tiezi, Li Si, Wang Er]

clear()

It should be clear by looking at the name. 从此列表中删除所有元素After this call returns, the list will be empty, no Null.

public static void testClear() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    System.out.println("执行 clear() 前,arrayList.size=" + arrayList.size());
    arrayList.clear();
    System.out.println("执行 clear() 后,arrayList.size=" + arrayList.size());
}

Output:

Before executing clear(), arrayList.size=3
After executing clear(), arrayList.size=0

clone()

Before explaining this, let’s give an example.
image.png
Copying an object

public static void testCloneTemp() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    ArrayList<String> arrayList2 = arrayList;
    arrayList.add("混子");
    arrayList2.add("王多鱼");
    System.out.println(arrayList2);
}

Output:

[Zhang San, Li Si, Wang Er, Huan Zi, Wang Duoyu]
The effect we actually want to achieve is arrayList2no 混子, just need 王多鱼. But we made =the physical addresses of the two of them point to the same one, which is reflected at this time. Here comes the importance of clone.

public static void testClone() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    ArrayList<String> arrayList2 = (ArrayList<String>) arrayList.clone();
    arrayList.add("混子");
    arrayList2.add("王多鱼");
    System.out.println(arrayList2);
}

Output:

[Zhang San, Li Si, Wang Er, Wang Duoyu]
This way they will not affect each other.

contains(Object o)

元素oReturn if the list contains it true, otherwise return false;

public static void testContains() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    boolean existMazi = arrayList.contains("麻子");
    boolean existZhangsan = arrayList.contains("张三");
    System.out.printf("存在张三:%s,存在麻子:%s%n", existZhangsan, existMazi);
}

Output:

The existence of Zhang San: true, the existence of Mazi: false

ensureCapacity(int size)

The changed ArrayListcapacity is size.

public static void testChangeCapacity() throws NoSuchFieldException, IllegalAccessException {
    
    
    ArrayList<String> arrayList = new ArrayList<>(100);
    int sizeBefore = getCapacity(arrayList);
    arrayList.ensureCapacity(1000);
    int sizeAfter = getCapacity(arrayList);
    System.out.printf("更改前的size=%d,更改后的size=%d", sizeBefore, sizeAfter);
}

Output:

The size=100 before the change and the size=1000
method after the change are custom methods getCapacityto obtain the capacity, as follows:ArrayList

public static int getCapacity(ArrayList<?> arrayList) throws NoSuchFieldException, IllegalAccessException {
    
    
    Class<ArrayList> arrayListClass = ArrayList.class;
    Field field = arrayListClass.getDeclaredField("elementData");
    field.setAccessible(true);
    Object[] objects = (Object[]) field.get(arrayList);
    return objects.length;
}

forEach method iterates through the collection

Don't use the and method forEachat the same time , otherwise an exception will be reported. As for why, I won't explain it in detail here, because I haven't understood it yet. Let me know it in the comments after searching.removeadd

image.png
It is quite convenient to use, just use the above method, just don’t call the add and delete methods.

get(int index)

下标Get the corresponding subscript according to .

public static void testGet(){
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    for (int i = 0; i < arrayList.size(); i++) {
    
    
        String valueByIndex = arrayList.get(i);
        System.out.println(valueByIndex);
    }
}

Output:

Zhang
San Li Si
Wang Er

indexOf()

Get the corresponding subscript based on the value.

public static void testindexOf() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    System.out.printf("获取李四的下标:%d%n", arrayList.indexOf("张三"));
    System.out.printf("获取李四一的下标:%d%n", arrayList.indexOf("李四一"));
}

Output:

Get the subscript of Li Si: 0
Get the subscript of Li Siyi: -1

isEmpty()

Determine whether it is an empty collection, return empty true, otherwise return otherwise true. Cannot be used null.

public static void testIsEmpty() {
    
    
    ArrayList<String> arrayList = new ArrayList<>(100);
    System.out.printf("获取是否为空集合:%s%n", arrayList.isEmpty());
}

Output:

Get whether it is an empty collection: true

iterator()

To obtain 迭代器, use an iterator to traverse the collection. 只能使用一次Secondary use requires re-acquisition. For example, in the code I commented below, it will have no effect if it is used again.

public static void testIterator() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    Iterator<String> iterator = arrayList.iterator();
    while (iterator.hasNext()){
    
    
        String str = iterator.next();
        System.out.println(str);
        if("张三".equals(str)){
    
    
            iterator.remove();
        }
    }
    // while (iterator.hasNext())
    System.out.println(arrayList);
}

Output:

Zhang
San Li Si
[Li Si]

lastIndexOf(Object o)

Returns the subscript of the last occurrence of the specified object in this collection. If the object is found, return it. If 下标the object cannot be found, return it -1.

public static void testLastIndexOf() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("张三");
    int lastIndexZs = arrayList.lastIndexOf("张三");//应该返回2
    int lastIndexLsy = arrayList.lastIndexOf("李四一");
    System.out.printf("张三最后出现的下标为:%d,李四一最后出现的下标为:%d%n", lastIndexZs, lastIndexLsy);
}

Output:

The last subscript for Zhang San is: 2, and the last subscript for Li Siyi is: -1

listIterator()

Like iteratorthe upgraded version, it can 正逆向遍历support modifying data during the traversal process, such as set, remove, add.

public static void testListIterator() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    ListIterator<String> listIterator = arrayList.listIterator();
    String firstIndex = listIterator.next();
    System.out.printf("开始删除:%s,arrayList:%s%n", firstIndex, arrayList);
    listIterator.remove();
    System.out.printf("删除后,arrayList%s%n" , arrayList);
    listIterator.add("张三");
    listIterator.next();
    listIterator.set("李四替身");
    System.out.printf("set后,arrayList%s%n" , arrayList);
    int prevIndex = listIterator.previousIndex();
    System.out.printf("获取上一个元素的下标%d%n" , prevIndex);
    listIterator.previous();
    listIterator.set("张三替身");
    System.out.printf("set后,arrayList%s%n" , arrayList);
}

Output:

Start deleting: Zhang San, arrayList: [Zhang San, Li Si]
After deletion, arrayList [Li Si]
set, arrayList [Zhang San, Li Si substitute]
gets the subscript 1 of the previous element
. After set, arrayList [Zhang San] , Zhang San's stand-in]

listIterator(int index)

Start traversing from the specified index.

public static void testListIteratorStartIndex() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王二");
    // 因法外狂徒张三入狱,只取后面的值
    ListIterator<String> iterator = arrayList.listIterator(1);
    while (iterator.hasNext()) {
    
    
        System.out.println(iterator.next());
    }
}

Output:

Li Si
Wang Er

remove(int index)

Remove an object by subscript. If the entered subscript does not exist, IndexOutOfBoundsExceptionan exception will occur. If the removal is successful, the object will be returned.

public static void testRemove() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    String removeStr = arrayList.remove(1);
    System.out.println(removeStr);
}

Output:

John Doe

remove(Object obj)

Remove the object. After testing, only the first matching value will be removed. If the removal is successful, it will be returned true, otherwise it will be returned false.

public static void testRemoveByObject() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("张三");
    arrayList.add(null);
    System.out.printf("arrayList.remove("张三")返回=%s%n",arrayList.remove("张三"));
    System.out.printf("arrayList=%s%n",arrayList);
}

Output:

arrayList.remove("Zhang San") returns =true
arrayList=[李思, Zhang San, null]

removeAll(Collection<?> c)

Removes objects from the passed collection.

public static void testremoveAll() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("张三");
    arrayList.removeAll(new ArrayList<String>() {
    
    {
    
    
        add("张三");
    }});
    System.out.printf("arrayList=%s%n", arrayList);
}

Output:

arrayList=[李思]

removeIf()

Delete objects that meet certain conditions.

public static void testRemoveIf() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("张三");
    System.out.printf("删除张三前,arrayList=%s%n", arrayList);
    arrayList.removeIf("张三"::equals);
    System.out.printf("删除张三后,arrayList=%s%n", arrayList);
}

Output:

Before deleting Zhang San, arrayList=[Zhang San, Li Si, Zhang San]
After deleting Zhang San, arrayList=[Li Si]

replaceAll()

Replace elements, such as converting all elements in a collection to uppercase, or performing calculations on all elements.

public static void testReplaceAll() {
    
    
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("张三");
    arrayList.add("李四");
    arrayList.add("王五");
    arrayList.add("赵六");
    arrayList.replaceAll(item -> "姓名:" + item);
    System.out.printf("arrayList=%s%n", arrayList);
}

Output:

arrayList=[Name: Zhang San, Name: Li Si, Name: Wang Wu, Name: Zhao Liu]

retainAll(Collection<?> c)

Take the union of two sets and eliminate elements that do not exist in both sets;

public static void testRetainAll() {
    
    
    ArrayList<String> arrayList = new ArrayList<String>() {
    
    {
    
    
        add("张三");
        add("李四");
        add("王五");
        add("赵六");
    }};
    arrayList.retainAll(Arrays.asList("王五", "赵六"));
    System.out.printf("arrayList=%s%n", arrayList);
}

Output:

arrayList=[Wang Wu, Zhao Liu]

set(int index, E element)

Replace or insert objects based on the subscript. For example, set the value of
the subscript in the collection to .1鲁班七号

public static void testSet() {
    
    
    ArrayList<String> arrayList = new ArrayList<String>() {
    
    {
    
    
        add("张三");
        add("李四");
        add("王五");
        add("赵六");
    }};
    System.out.printf("设置前,arrayList=%s%n", arrayList);
    arrayList.set(1,"鲁班七号");
    System.out.printf("设置后,arrayList=%s%n", arrayList);
}

The output result of method execution is:

Before setting, arrayList=[Zhang San, Li Si, Wang Wu, Zhao Liu]
After setting, arrayList=[Zhang San, Luban No. 7, Wang Wu, Zhao Liu]

size()

Returns the number of data items in the collection.

sort(Comparator<? super E> c)

Sort the objects in the collection in a specified way.

public static void testSort() {
    
    
    ArrayList<Integer> arrayList = new ArrayList<Integer>() {
    
    {
    
    
        add(100);
        add(200);
        add(40);
        add(80);
    }};
    System.out.printf("排序前,arrayList=%s%n", arrayList);
    arrayList.sort(Comparator.naturalOrder());
    System.out.printf("自然顺序排列后,arrayList=%s%n", arrayList);
    arrayList.sort(Comparator.reverseOrder());
    System.out.printf("倒序排列后,arrayList=%s%n", arrayList);
}

The output result of method execution is:

Before sorting, arrayList=[100, 200, 40, 80]
After sorting in natural order, arrayList=[40, 80, 100, 200]
After sorting in reverse order, arrayList=[200, 100, 80, 40]

spliterator()

Parallel iterator is to put the objects in the collection into the iterator.
Then, you can start multiple threads to process these objects in parallel.
The sample code is as follows:

public static void testSpliterator() {
    
    
    ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6));

    Spliterator<Integer> sItr = arrayList.spliterator();
    // 遍历后迭代器中的值也会消失
    // sItr.forEachRemaining(d -> System.out.print(d));   //123456
    new Thread(() -> {
    
    
        for (int i = 0; i < 4; i++) {
    
    
            sItr.tryAdvance(d -> System.out.printf("线程:%s,抢到了:%d%n", Thread.currentThread().getName(), d));
        }
    }).start();
    new Thread(() -> {
    
    
        for (int i = 0; i < 4; i++) {
    
    
            sItr.tryAdvance(d -> System.out.printf("线程:%s,抢到了:%d%n", Thread.currentThread().getName(), d));
        }
    }).start();
}

The output result of method execution is:

线程:Thread-0,抢到了:1
线程:Thread-0,抢到了:3
线程:Thread-0,抢到了:4
线程:Thread-0,抢到了:5
线程:Thread-1,抢到了:2
线程:Thread-1,抢到了:6

subList(int formIndex,int toIndex)

Intercepts a portion of a collection and returns a Listcollection.

image.png

The picture comes from the novice tutorial.
The sample code is as follows:

public static void testSubList() {
    
    
    ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("p", "r", "o", "g", "r", "a", "m"));
    List<String> subList1 = arrayList.subList(0, 7);
    System.out.printf("arrayList.subList(0,7) result:%s%n", subList1);
    List<String> subList2 = arrayList.subList(3, 7);
    System.out.printf("arrayList.subList(3,7) result:%s%n", subList2);
    List<String> subList3 = arrayList.subList(3, 6);
    System.out.printf("arrayList.subList(3,6) result:%s%n", subList3);
}

The output result of method execution is:

arrayList.subList(0,7) result:[p, r, o, g, r, a, m]
arrayList.subList(3,7) result:[g, r, a, m]
arrayList.subList(3,6) result:[g, r, a]

toArray() && toArray(T[] a)

Returns an array 当前集合顺序排列containing ArrayListall elements in .
The sample code is as follows:

public static void testToArray() {
    
    
    // 1. toArray()
    ArrayList<Integer> arrayList = new ArrayList<>(Arrays.asList(10, 20, 3, 41, 15, 26));
    Object[] num = arrayList.toArray();
    System.out.println(Arrays.toString(num));
    // 2. toArray(T[] a)
    Integer[] arr = new Integer[arrayList.size()];
    arr = arrayList.toArray(arr);
    System.out.println(Arrays.toString(arr));
}

The output result of method execution is:

[10, 20, 3, 41, 15, 26]
[10, 20, 3, 41, 15, 26]

trimToSize()

Remove excess capacity from ArrayList.
The sample code is as follows:

public static void testTrimToSize() throws NoSuchFieldException, IllegalAccessException {
    
    
    ArrayList<Integer> arrayList = new ArrayList<>(100);
    arrayList.add(11);
    arrayList.add(12);
    arrayList.add(13);
    System.out.printf("trimToSize之前ArrayList容量大小:%d%n", getCapacity(arrayList));
    arrayList.trimToSize();
    System.out.printf("trimToSize之后ArrayList容量大小:%d%n", getCapacity(arrayList));
}

The output result of method execution is:

trimToSize之前ArrayList容量大小:100
trimToSize之后ArrayList容量大小:3

Finished writing Liao

No need to memorize it by rote, save it as a dictionary and look it up.
The address of the above code
is https://github.com/cuifuan/house/blob/master/src/test/java/com/home/test/TestArrayListFun.java

QQ picture 20171201143204.jpg
Farewell!

Guess you like

Origin blog.csdn.net/Fine_Cui/article/details/119247966
Recommended