Java foundation -- complete solution of ArrayList method (Dictionary version)

introduction

When using the collection ArrayList, you often use add, remove, etc. there are many others you haven't used or even heard of Now in this tutorial, simply understand it. You don't need to write it all down It's equivalent to building an index in your head, that is, when some methods are used, don't build wheels repeatedly

The ArrayList structure is as follows


There are 33 construction methods in total

start

The following methods are ranked in no order

ArrayList()

You can create an ArrayList collection using new ArrayList(), as follows:

/**
 * 1 Simple ArrayList
 */
public static ArrayList getArrayList(){
    ArrayList arrayList = new ArrayList();
    arrayList.add("Zhang San");
    arrayList.add("Reese");
    return arrayList;
}

Some editors will report yellow lines or light yellow background prompts, as shown in the following figure


This requires a type for ArrayList, such as ArrayList < string >

ArrayList(Collection<? extends E> c)

You can put an aggregate to initialize ArrayList. The example code is as follows:

HashSet<String> temp1 = new HashSet<>();
temp1.add("Zhang San");
temp1.add("Reese");
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 to directly define the capacity when you know the amount of data stored in the set, so as to avoid the waste of resources due to the self increasing space of the set

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

add() and add(int, E)

The add() method adds the value in parentheses to the end of the collection
add(int, E) is the specific subscript to insert data. The following table starts from zero

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Zhang San");
arrayList.add(0,"In the day");
arrayList.add("Reese");
arrayList.forEach(System.out::println);

addAll(Collection<? extends E> c)

All elements in the set are appended to the end of this list;

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Zhang San");
arrayList.add("Li Si");
arrayList.add("WangTwo ");
ArrayList<String> arrayList2 = new ArrayList<>();
arrayList2.add("Pockmarks");
arrayList2.add("Iron son");
arrayList.addAll(arrayList2);
System.out.println(arrayList);

Output:

[Zhang San, Li Si, Wang Er, Ma Zi, tie Zi]

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

It is equivalent to the combined version of add(int index,E) and addall (collection <? Extensions E > C)
Appends all the elements in the specified set in sequence at the specified index subscript For example, in the last example, I want to jump in the line behind Zhang San, so let's do it

public static void testAddAllByIndex(){
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    ArrayList<String> arrayList2 = new ArrayList<>();
    arrayList2.add("Pockmarks");
    arrayList2.add("Iron son");
    arrayList.addAll(1,arrayList2);
    System.out.println(arrayList);
}

Output:

[Zhang San, Ma Zi, tie Zi, Li Si, Wang Er]

clear()

It should be clear from the name Remove all elements from this list When this call returns, the list will be empty, not Null

public static void testClear() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    System.out.println("implement clear() front,arrayList.size=" + arrayList.size());
    arrayList.clear();
    System.out.println("implement clear() after,arrayList.size=" + arrayList.size());
}

Output:

Before executing clear(), ArrayList size=3
After executing clear(), ArrayList size=0

clone()

Before explaining this, let's take a chestnut

Copy Object

public static void testCloneTemp() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    ArrayList<String> arrayList2 = arrayList;
    arrayList.add("Bastard");
    arrayList2.add("Wang Duoyu");
    System.out.println(arrayList2);
}

Output:

[Zhang San, Li Si, Wang Er, hunzi, Wang Duoyu]
In fact, the effect we want to achieve is arrayList2. Don't mix children, just Wang Duoyu However, we make = so that their physical addresses point to the same one, which reflects the importance of clone

public static void testClone() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    ArrayList<String> arrayList2 = (ArrayList<String>) arrayList.clone();
    arrayList.add("Bastard");
    arrayList2.add("Wang Duoyu");
    System.out.println(arrayList2);
}

Output:

[Zhang San, Li Si, Wang Er, Wang Duoyu]
So they won't affect each other

contains(Object o)

If the list contains elements o, it returns true; otherwise, it returns false;

public static void testContains() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    boolean existMazi = arrayList.contains("Pockmarks");
    boolean existZhangsan = arrayList.contains("Zhang San");
    System.out.printf("There is Zhang San:%s,Presence of pockmarks:%s%n", existZhangsan, existMazi);
}

Output:

Zhang San: true, pockmarked: false

ensureCapacity(int size)

Change the capacity of ArrayList to 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("Before change size=%d,Changed size=%d", sizeBefore, sizeAfter);
}

Output:

Size before change = 100, size after change = 1000
Method getCapacity is a custom method to obtain the capacity size for ArrayList, as follows:

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

The forEach method traverses the collection

Do not use the remove and add methods while using forEach, or an exception will be reported
As for why, I won't talk about it here, because I haven't understood it yet. Search it and tell me in the comments


It's very convenient to use. Just don't call the add and delete methods

get(int index)

Obtain the value of the corresponding subscript according to the subscript

public static void testGet(){
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    for (int i = 0; i < arrayList.size(); i++) {
        String valueByIndex = arrayList.get(i);
        System.out.println(valueByIndex);
    }
}

Output:

Zhang San
Li Si
WangTwo

indexOf()

Get the corresponding subscript according to the value

public static void testindexOf() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    System.out.printf("Get the subscript of Li Si:%d%n", arrayList.indexOf("Zhang San"));
    System.out.printf("Get the subscript of Li Siyi:%d%n", arrayList.indexOf("Li Siyi"));
}

Output:

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

isEmpty()

Judge whether it is an empty collection. If it is empty, it returns true. Otherwise, it returns true Cannot be used for null

public static void testIsEmpty() {
    ArrayList<String> arrayList = new ArrayList<>(100);
    System.out.printf("Gets whether the collection is empty:%s%n", arrayList.isEmpty());
}

Output:

Gets whether the collection is empty: true

iterator()

Get the iterator and use the iterator to traverse the collection It can only be used once, and it needs to be obtained again for secondary use For example, where I annotate the following code, it has no effect to use it again

public static void testIterator() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    Iterator<String> iterator = arrayList.iterator();
    while (iterator.hasNext()){
        String str = iterator.next();
        System.out.println(str);
        if("Zhang San".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, the subscript is returned, and - 1 is returned if the object is not found

public static void testLastIndexOf() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("Zhang San");
    int lastIndexZs = arrayList.lastIndexOf("Zhang San");//Should return 2
    int lastIndexLsy = arrayList.lastIndexOf("Li Siyi");
    System.out.printf("Zhang San's last subscript is:%d,Li Siyi's last subscript is:%d%n", lastIndexZs, lastIndexLsy);
}

Output:

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

listIterator()

Like an upgraded version of iterator, you can traverse forward and backward Support data modification during traversal, such as set, remove, add

public static void testListIterator() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    ListIterator<String> listIterator = arrayList.listIterator();
    String firstIndex = listIterator.next();
    System.out.printf("Start deletion:%s,arrayList:%s%n", firstIndex, arrayList);
    listIterator.remove();
    System.out.printf("After deletion,arrayList%s%n" , arrayList);
    listIterator.add("Zhang San");
    listIterator.next();
    listIterator.set("Li Si double");
    System.out.printf("set after,arrayList%s%n" , arrayList);
    int prevIndex = listIterator.previousIndex();
    System.out.printf("Gets the subscript of the previous element%d%n" , prevIndex);
    listIterator.previous();
    listIterator.set("Zhang San double");
    System.out.printf("set after,arrayList%s%n" , arrayList);
}

Output:

Start deleting: Zhang San, arrayList: [Zhang San, Li Si]
After deletion, arrayList [Li Si]
After set, arrayList [Zhang San, Li Si doubles]
Gets the subscript 1 of the previous element
After set, arrayList [Zhang San, Zhang San double]

listIterator(int index)

Start traversal from the specified subscript

public static void testListIteratorStartIndex() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("WangTwo ");
    // Zhang San, a frenzied outlaw, is jailed. Only the latter value is taken
    ListIterator<String> iterator = arrayList.listIterator(1);
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

Output:

Li Si
WangTwo

remove(int index)

Remove the object by subscript. If the entry subscript does not exist, an IndexOutOfBoundsException exception will appear If the removal is successful, the object will be returned

public static void testRemove() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    String removeStr = arrayList.remove(1);
    System.out.println(removeStr);
}

Output:

Li Si

remove(Object obj)

Only the first matching value of the test object is removed true is returned if the removal is successful. false is returned if the removal is not successful

public static void testRemoveByObject() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("Zhang San");
    arrayList.add(null);
    System.out.printf("arrayList.remove("Zhang San")return=%s%n",arrayList.remove("Zhang San"));
    System.out.printf("arrayList=%s%n",arrayList);
}

Output:

arrayList.remove("Zhang San") returns = true
arrayList = [Li Si, Zhang San, null]

removeAll(Collection<?> c)

Removes objects from the incoming collection

public static void testremoveAll() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("Zhang San");
    arrayList.removeAll(new ArrayList<String>() {{
        add("Zhang San");
    }});
    System.out.printf("arrayList=%s%n", arrayList);
}

Output:

arrayList = [Li Si]

removeIf()

Delete objects that meet certain criteria

public static void testRemoveIf() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("Zhang San");
    System.out.printf("Delete Zhang Sanqian,arrayList=%s%n", arrayList);
    arrayList.removeIf("Zhang San"::equals);
    System.out.printf("After deleting Zhang San,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 the set to uppercase, or calculating all elements

public static void testReplaceAll() {
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Zhang San");
    arrayList.add("Li Si");
    arrayList.add("Wang Wu");
    arrayList.add("Zhao Liu");
    arrayList.replaceAll(item -> "full name:" + 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 the elements that do not exist in the two sets at the same time;

public static void testRetainAll() {
    ArrayList<String> arrayList = new ArrayList<String>() {{
        add("Zhang San");
        add("Li Si");
        add("Wang Wu");
        add("Zhao Liu");
    }};
    arrayList.retainAll(Arrays.asList("Wang Wu", "Zhao Liu"));
    System.out.printf("arrayList=%s%n", arrayList);
}

Output:

arrayList = [Wang Wu, Zhao Liu]

set(int index, E element)

Replace or insert objects according to subscripts
For example, set the value with subscript 1 in the set to Luban 7

public static void testSet() {
    ArrayList<String> arrayList = new ArrayList<String>() {{
        add("Zhang San");
        add("Li Si");
        add("Wang Wu");
        add("Zhao Liu");
    }};
    System.out.printf("Before setting,arrayList=%s%n", arrayList);
    arrayList.set(1,"Luban 7");
    System.out.printf("After setting,arrayList=%s%n", arrayList);
}

The output result of method operation 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 entries in the collection

sort(Comparator<? super E> c)

Sorts the objects in the collection in the specified way

public static void testSort() {
    ArrayList<Integer> arrayList = new ArrayList<Integer>() {{
        add(100);
        add(200);
        add(40);
        add(80);
    }};
    System.out.printf("Before sorting,arrayList=%s%n", arrayList);
    arrayList.sort(Comparator.naturalOrder());
    System.out.printf("After natural sequence,arrayList=%s%n", arrayList);
    arrayList.sort(Comparator.reverseOrder());
    System.out.printf("After reverse order,arrayList=%s%n", arrayList);
}

The output result of method operation is:

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

spliterator()

Parallel iterator is to put the objects in the collection into the iterator
You can then turn on multiple threads to process these objects in parallel
The example 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();
    // After traversal, the value in the iterator also disappears
    // sItr.forEachRemaining(d -> System.out.print(d));   //123456
    new Thread(() -> {
        for (int i = 0; i < 4; i++) {
            sItr.tryAdvance(d -> System.out.printf("thread :%s,Got it:%d%n", Thread.currentThread().getName(), d));
        }
    }).start();
    new Thread(() -> {
        for (int i = 0; i < 4; i++) {
            sItr.tryAdvance(d -> System.out.printf("thread :%s,Got it:%d%n", Thread.currentThread().getName(), d));
        }
    }).start();
}

The output result of method operation is:

thread :Thread-0,Got it:1
 thread :Thread-0,Got it:3
 thread :Thread-0,Got it:4
 thread :Thread-0,Got it:5
 thread :Thread-1,Got it:2
 thread :Thread-1,Got it:6

subList(int formIndex,int toIndex)

Intercepts a part of the set and returns a List set

Figure from rookie tutorial
The example 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 operation 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 that is in the current collection order and contains all the elements in the ArrayList
The example 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 operation is:

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

trimToSize()

Remove excess capacity from ArrayList
The example 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 before ArrayList Capacity size:%d%n", getCapacity(arrayList));
    arrayList.trimToSize();
    System.out.printf("trimToSize after ArrayList Capacity size:%d%n", getCapacity(arrayList));
}

The output result of method operation is:

trimToSize before ArrayList Capacity size:100
trimToSize after ArrayList Capacity size:3

Finish writing Liao

Don't memorize by rote. Collect it and look it up as a dictionary
Address of the above code
https://github.com/cuifuan/house/blob/master/src/test/java/com/home/test/TestArrayListFun.java


take leave!

Keywords: Java java8 arraylist

Added by Sooz719 on Tue, 04 Jan 2022 10:18:04 +0200