Tool and Resource Center

Help developers work more efficiently and provide tools and resources around the developer lifecycle

Developer.aliyun.com/tool?spm=a1…

The introduction

When using collectionsArrayList“, often usedadd,removeAnd so on, others have not used, even have not heard of there are many. Now in this tutorial, just take a quick look at it, and you don’t have to write it all down. It’s like building an index in your head, but there are some methods that don’t have to be repeated to build the wheel.

The ArrayList structure is as follows



The total number of including constructors is33A method.

start

The following methods are in no particular order

ArrayList()

You can create a collection of arrayLists using new ArrayList(), as follows:

Public static ArrayList getArrayList(){ArrayList ArrayList = new ArrayList(); ArrayList. Add (" * * "); ArrayList. Add (" list "); return arrayList; }Copy the code

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



This needs to be given toArrayListA type, for exampleArrayList<String> .

ArrayList(Collection<? extends E> c)

You can initialize an ArrayList by putting it into an aggregate. The example code looks like this:

HashSet<String> temp1 = new HashSet<>(); Temp1. Add (" * * "); Temp1. Add (" list "); ArrayList<String> arrayList2 = new ArrayList<>(temp1); arrayList2.forEach(System.out::println);Copy the code

ArrayList(int initialCapacity)

Construct an empty list with a specified initial capacity. When you have a rough idea of how much data the collection will hold, define the capacity directly to avoid wasting resources by increasing the collection space.

ArrayList<String> arrayList3 = new ArrayList<>(1000);
Copy the code

The add () and add (int, E)

The add() method increments the values in parentheses to the end of the set. Add (int, E) inserts data into the specific index, starting from zero.

ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (0, "in heaven"); ArrayList. Add (" list "); arrayList.forEach(System.out::println);Copy the code

addAll(Collection<? extends E> c)

Appends all elements of the collection to the end of the list;

ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); ArrayList<String> arrayList2 = new ArrayList<>(); ArrayList2. Add (" mike "); ArrayList2. Add (" iron "); arrayList.addAll(arrayList2); System.out.println(arrayList);Copy the code

Output:

[Zhang SAN, Li Si, Wang Er, Pozi, Tiezi]

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

Add (int index,E) and addAll(Collection
c) Extends E> c) Appends all the elements in a specified collection at the specified index index. For example, in the last example, I want to put pockmarks and iron sons in the back of the three, so such as down to achieve.

public static void testAddAllByIndex(){ ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); ArrayList<String> arrayList2 = new ArrayList<>(); ArrayList2. Add (" mike "); ArrayList2. Add (" iron "); arrayList.addAll(1,arrayList2); System.out.println(arrayList); }Copy the code

Output:

[Zhang SAN, Pozi, Tiezi, 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 (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); System.out.println(" before clear(),arrayList.size=" + arrayList.size()); arrayList.clear(); System.out.println(" arrayList.size=" + arrayList.size())); }Copy the code

Output:

Before clear(),arrayList.size=3 after clear(),arrayList.size=0

clone()

Before we do that, let’s take a chestnut.



Copy the object

public static void testCloneTemp() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); ArrayList<String> arrayList2 = arrayList; ArrayList. Add (" slackers "); ArrayList2. Add (" wangduo fish "); System.out.println(arrayList2); }Copy the code

Output:

[Zhang SAN, Li Si, Wang Er, Mix, Wang Duoyu] What we really want to achieve is arrayList2 does not mix, only need wang duoyu. However, we set =, which led to the physical address of both of them pointing to the same location, which reflected the importance of clone.

public static void testClone() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); ArrayList<String> arrayList2 = (ArrayList<String>) arrayList.clone(); ArrayList. Add (" slackers "); ArrayList2. Add (" wangduo fish "); System.out.println(arrayList2); }Copy the code

Output:

[Zhang SAN, Li Si, Wang Er, Wang Duoyu] so that they don’t affect each other.

contains(Object o)

Return true if the list contains o, false if it does not;

public static void testContains() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); Boolean existMazi = arrayList.contains(" contains "); Boolean existMazi = arrayList.contains(" contains "); Boolean existZhangsan = arrayList.contains(" contains three "); Boolean existZhangsan = arrayList.contains(" contains three "); Printf (" existZhangsan :%s, existMazi :%s%n", existZhangsan, existMazi); }Copy the code

Output:

If there are three :true, if there are asako :false

ensureCapacity(int size)

Change the capacity of the 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(" size=%d, size=%d", sizeBefore, sizeAfter); }Copy the code

Output:

GetCapacity is a custom method to obtain the capacity of an 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; }Copy the code

The forEach method traverses the collection

Do not use the remove and add methods with forEach, otherwise exceptions will be reported. As to why, I won’t go into it here because I don’t understand it yet, so search it and let me know in the comments.



Use pretty convenient, is the use of the above method, just do not call the new and delete method.

get(int index)

Get the value of the corresponding subscript according to the subscript.

public static void testGet(){ ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); for (int i = 0; i < arrayList.size(); i++) { String valueByIndex = arrayList.get(i); System.out.println(valueByIndex); }}Copy the code

Output:

Three zhang li four Wang two

indexOf()

Gets the corresponding subscript from the value.

public static void testindexOf() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); System.out.printf(" getlist.indexof (%d%n) ", arrayList.indexof (" getlist.indexof ")); System.out.printf(" getlist.indexof (%d%n) ", arrayList.indexof (" getlist.indexof ")); }Copy the code

Output:

Obtain the subscript of Li Si :0 Obtain the subscript of Li Si yi :-1

isEmpty()

Returns true if it is an empty set, or true otherwise. Cannot be used for null.

public static void testIsEmpty() { ArrayList<String> arrayList = new ArrayList<>(100); System.out.printf(" get null set :%s%n", arrayList.isempty ()); }Copy the code

Output:

Gets whether the collection is empty :true

iterator()

Get an iterator and use it to traverse the collection. This parameter can be used only once and must be obtained again. For example, the following code I commented on the place, to use again has no effect.

public static void testIterator() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); Iterator<String> iterator = arrayList.iterator(); while (iterator.hasNext()){ String str = iterator.next(); System.out.println(str); If (" iterator.remove ".equals(STR)){iterator.remove(); } } // while (iterator.hasNext()) System.out.println(arrayList); }Copy the code

Output:

Zhang SAN li Si

lastIndexOf(Object o)

Returns the subscript of the last occurrence of the specified object in this collection. Return the index if an object is found, or -1 if no object is found.

public static void testLastIndexOf() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" * * "); Int lastIndexZs = arrayList.lastIndexof (" "); // Should return 2 int lastIndexLsy = arrayList.lastIndexof (" li si yi "); Printf (" %d%n", lastIndexZs, lastIndexLsy); printf(" %d%n", lastIndexZs, lastIndexLsy); }Copy the code

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 go backwards and forwards. Data can be modified during traversal, such as set, remove, and add.

public static void testListIterator() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ListIterator<String> listIterator = arrayList.listIterator(); String firstIndex = listIterator.next(); System.out.printf(" start delete :%s,arrayList:%s%n", firstIndex, arrayList); listIterator.remove(); System.out.printf(" delete,arrayList%s%n",arrayList); ListIterator. Add (" * * "); listIterator.next(); Listiterator. set(" li si double "); System.out.printf(" after set,arrayList%s%n",arrayList); int prevIndex = listIterator.previousIndex(); System.out.printf(" get the subscript %d%n of the last element ", prevIndex); listIterator.previous(); Listiteratator. set(" triple double "); System.out.printf(" after set,arrayList%s%n",arrayList); }Copy the code

Output:

ArrayList [arrayList] = arrayList[arrayList] = arrayList[arrayList] = arrayList[arrayList] = arrayList[arrayList] = arrayList[arrayList] = arrayList[arrayList] = arrayList[arrayList]

listIterator(int index)

Starting at the specified index.

public static void testListIteratorStartIndex() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" two "); ListIterator<String> iterator = arrayList.listiterator (1); while (iterator.hasNext()) { System.out.println(iterator.next()); }}Copy the code

Output:

Li si two

remove(int index)

By subscript remove object into the subscript, if does not exist, there will be a IndexOutOfBoundsException anomalies. The object is returned when the removal succeeds.

public static void testRemove() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); String removeStr = arrayList.remove(1); System.out.println(removeStr); }Copy the code

Output:

Li si

remove(Object obj)

Removing an object will remove only the first value that matches the test. Return true if removal succeeds, false if removal fails.

public static void testRemoveByObject() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" * * "); arrayList.add(null); System.out.printf("arrayList.remove(" threes ") return =%s%n",arrayList.remove(" threes ")); System.out.printf("arrayList=%s%n",arrayList); }Copy the code

Output:

Return =true arrayList=[li4, li3, null]

removeAll(Collection<? > c)

Removes objects from the passed collection.

public static void testremoveAll() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" * * "); Arraylist.removeall (new arrayList <String>() {{add(" add three "); }}); System.out.printf("arrayList=%s%n", arrayList); }Copy the code

Output:

ArrayList = [bill]

removeIf()

Deletes objects that meet specific conditions.

public static void testRemoveIf() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" * * "); Printf (" arrayList=%s%n", arrayList); system.out. printf(" arrayList=%s%n", arrayList); ArrayList. RemoveIf (" zhang ": : equals); System.out.printf(" arrayList=%s%n", arrayList); }Copy the code

Output:

ArrayList =[arrayList=[arrayList=[arrayList=[arrayList]]

replaceAll()

Replace elements, such as turning all elements in the set to uppercase, or evaluating all elements.

public static void testReplaceAll() { ArrayList<String> arrayList = new ArrayList<>(); ArrayList. Add (" * * "); ArrayList. Add (" li si "); ArrayList. Add (" detective "); ArrayList. Add (" Daisy "); Arraylist.replaceall (item -> "name :" + item); System.out.printf("arrayList=%s%n", arrayList); }Copy the code

Output:

ArrayList =[Name: Zhang SAN, Name: Li Si, Name: Wang Wu, Name: Zhao Liu]

retainAll(Collection<? > c)

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

Public static void testRetainAll() {ArrayList<String> ArrayList = new ArrayList<String>() {{add(" three "); Add (" li si "); Add (" detective "); Add (" Daisy "); }}; Arraylist. retainAll(Arrays.aslist (" Arrays.aslist ")); System.out.printf("arrayList=%s%n", arrayList); }Copy the code

Output:

ArrayList =[wang 5, Zhao 6]

set(int index, E element)

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

Public static void testSet() {ArrayList<String> ArrayList = new ArrayList<String>() {{add(" span "); Add (" li si "); Add (" detective "); Add (" Daisy "); }}; System.out.printf(" before setting,arrayList=%s%n", arrayList); Arraylist. set(1," luban 7 "); System.out.printf(" after setting,arrayList=%s%n", arrayList); }Copy the code

The output of the method is:

ArrayList =[zhang SAN, Lu Ban no. 7, Wang Wu, Zhao Vi]

size()

Returns the number of items in a collection.

sort(Comparator<? super E> c)

Sorts objects in a collection in a specified manner.

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()); Printf (" arrayList=%s%n", arrayList); system.out. printf(" arrayList=%s%n", arrayList); arrayList.sort(Comparator.reverseOrder()); System.out.printf(" arrayList=%s%n", arrayList); }Copy the code

The output of the method is:

ArrayList =[100, 200, 40, 80] arrayList=[40, 80, 100, 200] arrayList=[200, 100, 80, 40]

spliterator()

Parallel iterators, you put the objects in the collection into iterators. You can then start 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(); Sitr. forEachRemaining(d -> system.out.print (d)); //123456 new Thread(() -> { for (int i = 0; i < 4; Printf (" Thread :%s, %d%n", thread.currentThread ().getName(), d)); } }).start(); new Thread(() -> { for (int i = 0; i < 4; Printf (" Thread :%s, %d%n", thread.currentThread ().getName(), d)); } }).start(); }Copy the code

The output of the method is:

Thread: thread-0, captured :1 Thread: thread-0, captured :3 Thread: thread-0, captured :4 Thread: thread-0, captured :5 Thread: thread-1, captured :2 Thread: thread-1, captured :6. Thread: thread-0, captured :3 Thread: thread-0, captured :4 Thread: thread-0, captured :5 Thread: thread-1, captured :2 Thread: thread-1, captured :6Copy the code

subList(int formIndex,int toIndex)

Intercepts part of a collection and returns a List collection.

Figure from the novice tutorial sample code:

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. The out. Printf (" arrayList subList (0, 7) result: % s % n ", subList1); List<String> subList2 = arrayList.subList(3, 7); System. The out. Printf (" arrayList subList (3, 7) result: % s % n ", subList2); List<String> subList3 = arrayList.subList(3, 6); System. The out. Printf (" arrayList subList (3, 6) result: % s % n ", subList3); }Copy the code

The output of the method is:

SubList (0,7) result:[p, r, o, g, r, a, m] 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 of 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 and 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)); }Copy the code

The output of the method is:

[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(" ArrayList capacity before trimToSize :%d%n", getCapacity(ArrayList)); arrayList.trimToSize(); System.out.printf(" ArrayList capacity after trimToSize :%d%n", getCapacity(ArrayList)); }Copy the code

The output of the method is:

Capacity of ArrayList before trimToSize :100 Capacity of ArrayList after trimToSize :3Copy the code

Finish the liao

Don’t memorize it by rote. Keep it as a dictionary. The address of the above code github.com/cuifuan/hou…



Say goodbye!