Java ArrayList

Java ArrayList is one of the most widely used Collection class. java.util.ArrayList class implements java.util.List interface. Java ArrayList also implements RandomAccess, Cloneable and Serializable interfaces. Java ArrayList class extends AbstractList class that is the skeleton implementation of List interface.

Java ArrayList是使用最广泛的Collection类之一。 java.util.ArrayList类实现java.util.List接口。 Java ArrayList还实现RandomAccess,Cloneable和Serializable接口。 Java ArrayList类扩展了AbstractList类,该类是List接口的基本实现。

Java ArrayList (Java ArrayList)

Java ArrayList is the resizable array implementation of List interface, that means it starts with default size and grows automatically when more data is added into array list. Some important points about Java ArrayList are:

Java ArrayList是List接口的可调整大小的数组实现,这意味着它以默认大小开始,并在向数组列表中添加更多数据时自动增长。 关于Java ArrayList的一些重要点是:

  • Java ArrayList is almost similar to Vector except that it’s unsynchronized, so performance is better in single threaded environment.

    Java ArrayList除了不同步外,几乎与Vector相似,因此在单线程环境中性能更好。
  • Java ArrayList is not thread safe, so special care must be given when used in multithreaded environment.

    Java ArrayList不是线程安全的,因此在多线程环境中使用时必须格外小心。
  • Java ArrayList can contain duplicate values, it also allows “null” value.

    Java ArrayList可以包含重复值,它也允许“空”值。
  • Objects in java ArrayList are added in order. So you can always retrieve the first object by index 0.

    java ArrayList中的对象按顺序添加。 因此,您始终可以按索引0检索第一个对象。
  • Java ArrayList default capacity is defined as 10. However we can change the default capacity through it’s constructor or by calling ensureCapacity(int minCapacity) method.

    Java ArrayList的默认容量定义为10。但是,我们可以通过其构造函数或调用ensureCapacity(int minCapacity)方法来更改默认容量。
  • Java ArrayList Iterator and ListIterator implementation is fail-fast. If the list structure is modified after creating the iterator in any other way except the iterator add or remove methods, it will throw ConcurrentModificationException.

    Java ArrayList Iterator和ListIterator实现是快速失败的 。 如果在创建迭代器之后以除迭代器add或remove方法之外的任何其他方式修改了列表结构,则它将抛出ConcurrentModificationException
  • Java ArrayList provides random access to it’s elements because it works on index. We can retrieve any element through it’s index.

    Java ArrayList提供了对其元素的随机访问,因为它对索引有效。 我们可以通过其索引检索任何元素。
  • Java ArrayList supports Generics and it’s the recommended way to create an ArrayList.
    List list = new ArrayList(); //not recommended
    List<String> list1 = new ArrayList<String>(); // recommended way

    Java ArrayList支持泛型,这是创建ArrayList的推荐方法。

Java ArrayList构造函数 (Java ArrayList Constructors)

There are three constructors in Java ArrayList class.

Java ArrayList类中有三个构造函数。

  1. public ArrayList(): Most widely used Java ArrayList constructor. This ArrayList constructor will return an empty list with initial capacity of 10.

    public ArrayList() :最广泛使用的Java ArrayList构造函数。 此ArrayList构造函数将返回一个初始容量为10的空列表。
  2. public ArrayList(int initialCapacity): This ArrayList constructor will return an empty list with initial capacity as specified by the initialCapacity argument. This constructor is useful when you know that your list will contain huge data and you want to save time of reallocation by providing a large value of initial capacity. If the initialCapacity argument is negative, it will throw IllegalArgumentException.

    public ArrayList(int initialCapacity) :此ArrayList构造函数将返回一个空列表,其初始容量由initialCapacity参数指定。 当您知道列表将包含大量数据并且希望通过提供较大的初始容量值来节省重新分配的时间时,此构造函数很有用。 如果initialCapacity参数为负,则将抛出IllegalArgumentException
  3. public ArrayList(Collection<? extends E> c): This ArrayList constructor will return a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator. It will throw famous NullPointerException if the specified collection argument is null.

    public ArrayList(Collection <?extends E> c) :此ArrayList构造函数将返回一个列表,该列表包含指定集合的​​元素,此列表按集合的迭代器返回的顺序排列。 如果指定的collection参数为null,它将抛出著名的NullPointerException

Below is a simple code snippet showing Java ArrayList constructors in use.

以下是显示正在使用的Java ArrayList构造函数的简单代码段。

// Java ArrayList default constructor
List<String> vowels = new ArrayList<String>();

//Java ArrayList constructor with initial capacity
List<String> dictionaryWordsList = new ArrayList<String>(50000);

vowels.add("A");
vowels.add("B");
vowels.add("C");
vowels.add("D");
vowels.add("E");

//Creating my list from different collection source
List<String> myList = new ArrayList<String>(vowels);

Java ArrayList方法 (Java ArrayList Methods)

Java ArrayList contains many methods that we use regularly.

Java ArrayList包含许多我们经常使用的方法。

  1. public boolean add(E e): Appends the specified element to the end of this list.

    public boolean add(E e) :将指定的元素追加到此列表的末尾。
  2. public void add(int index, E element): Inserts the specified element at the specified position in the list. Shifts the element currently at that position (if any) and any subsequent elements to the right. If index is greater than list size or negative, it will throw IndexOutOfBoundsException.

    public void add(int index,E element) :将指定的元素插入列表中的指定位置。 将当前在该位置的元素(如果有)和任何后续元素右移。 如果index大于列表大小或为负数,它将抛出IndexOutOfBoundsException。
  3. public boolean addAll(Collection<? extends E> c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. This operation throws NullPointerException if the specified collection is null.

    public boolean addAll(Collection <?extends E> c) :将指定集合中的所有元素按指定集合的​​Iterator返回的顺序追加到此列表的末尾。 如果指定的集合为null,则此操作将引发NullPointerException。
  4. public boolean addAll(int index, Collection<? extends E> c): Inserts all of the elements in the specified collection into this list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). This method will throw IndexOutOfBoundsException if the index value is greater than list size or negative. This method also throws NullPointerException if specified collection is null.

    public boolean addAll(int index,Collection <?extends E> c) :从指定位置开始,将指定集合中的所有元素插入此列表。 将当前位于该位置的元素(如果有)和任何后续元素右移(增加其索引)。 如果索引值大于列表大小或为负,则此方法将抛出IndexOutOfBoundsException。 如果指定的collection为null,则此方法还会引发NullPointerException。
  5. public boolean contains(Object o): Returns true if this list contains the specified element.

    public boolean contains(Object o) :如果此列表包含指定的元素,则返回true。
  6. public void clear(): Removes all of the elements from this list.

    public void clear() :从此列表中删除所有元素。
  7. public void ensureCapacity(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

    public void sureCapacity(int minCapacity) :如有必要,增加此ArrayList实例的容量,以确保它至少可以容纳最小容量参数指定的元素数。
  8. public void forEach(Consumer<? super E> action): Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

    public void forEach(Consumer <?super E> action) :对Iterable的每个元素执行给定的操作,直到所有元素都已处理或该操作引发异常。
  9. public E get(int index): Returns the element at the specified position in this list.

    public E get(int index) :返回此列表中指定位置的元素。
  10. public boolean isEmpty(): Returns true if this list contains no elements.

    public boolean isEmpty() :如果此列表不包含任何元素,则返回true。
  11. public int indexOf(Object o): Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

    public int indexOf(Object o) :返回此列表中指定元素的首次出现的索引;如果此列表不包含该元素,则返回-1。
  12. public Iterator<E> iterator(): Returns an iterator over the elements in this list in proper sequence. The returned iterator is fail-fast.

    public Iterator <E> iterator() :以适当的顺序返回此列表中元素的迭代器。 返回的迭代器是快速失败的。
  13. public int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

    public int lastIndexOf(Object o) :返回指定元素在此列表中最后一次出现的索引;如果此列表不包含该元素,则返回-1。
  14. public ListIterator<E> listIterator(): Returns a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast.

    public ListIterator <E> listIterator() :返回此列表中元素的列表迭代器(按适当顺序)。 返回的列表迭代器是快速失败的。
  15. public ListIterator<E> listIterator(int index): Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one. This method throws IndexOutOfBoundsException if index value is greater than list size or negative.

    public ListIterator <E> listIterator(int index) :从列表中的指定位置开始(按正确顺序)返回此列表中元素的列表迭代器。 指定的索引指示首次调用next将返回的第一个元素。 最初调用previous将返回指定索引减一的元素。 如果索引值大于列表大小或为负数,则此方法将引发IndexOutOfBoundsException。
  16. public E remove(int index): Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

    public E remove(int index) :删除此列表中指定位置的元素。 将所有后续元素向左移动(从其索引中减去一个)。
  17. public boolean remove(Object o): Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.

    public boolean remove(Object o) :从列表中删除第一次出现的指定元素(如果存在)。 如果列表不包含该元素,则该元素不变。
  18. public boolean removeAll(Collection<E> c): Removes from this list all of its elements that are contained in the specified collection.

    public boolean removeAll(Collection <E> c) :从此列表中删除所有包含在指定集合中的元素。
  19. public boolean retainAll(Collection<E> c): Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.

    public boolean keepAll(Collection <E> c) :仅保留此列表中包含在指定集合中的元素。 换句话说,从该列表中删除所有未包含在指定集合中的元素。
  20. public boolean removeIf(Predicate<? super E> filter): Removes all of the elements of this collection that satisfy the given predicate.

    public boolean removeIf(Predicate <?super E> filter) :删除此集合中满足给定谓词的所有元素。
  21. public void replaceAll(UnaryOperator<E> operator): Replaces each element of this list with the result of applying the operator to that element.

    public void replaceAll(UnaryOperator <E> operator) :使用将该运算符应用于该元素的结果替换此列表中的每个元素。
  22. public int size(): Returns the number of elements in this list.

    public int size() :返回此列表中的元素数。
  23. public E set(int index, E element): Replaces the element at the specified position in this list with the specified element.

    public E set(int index,E element) :使用指定元素替换此列表中指定位置的元素。
  24. public List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

    public List <E> subList(int fromIndex,int toIndex) :返回列表的一部分在指定的fromIndex(包括)和toIndex(不包括)之间的视图。 返回列表由该列表支持,因此返回列表中的非结构更改会反映在此列表中,反之亦然。
  25. public Spliterator<E> spliterator(): Creates a late-binding and fail-fast Spliterator over the elements in this list.

    public Spliterator <E> splitter() :在此列表中的元素上创建后绑定和故障快速的Spliterator。
  26. public void sort(Comparator<? super E> c): Sorts this list according to the order induced by the specified Comparator.

    public void sort(Comparator <?super E> c) :根据指定Comparator引起的顺序对该列表进行排序。
  27. public void trimToSize(): Trims the capacity of this ArrayList instance to be the list’s current size. An application can use this operation to minimize the storage of an ArrayList instance.

    public void trimToSize() :将此ArrayList实例的容量调整为列表的当前大小。 应用程序可以使用此操作来最小化ArrayList实例的存储。
  28. public Object[] toArray(): Returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be “safe” in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.

    public Object [] toArray() :以正确的顺序(从第一个到最后一个元素)返回一个包含此列表中所有元素的数组。 返回的数组将是“安全的”,因为此列表不会保留对其的引用。 (换句话说,此方法必须分配一个新数组)。 因此,调用者可以自由修改返回的数组。
  29. public <T> T[] toArray(T[] a): Returns an array containing all of the elements in this list in proper sequence. If the list fits in the specified array, it is returned as is. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

    public <T> T [] toArray(T [] a) :以正确的顺序返回包含此列表中所有元素的数组。 如果列表适合指定的数组,则按原样返回。 否则,将使用指定数组的运行时类型和此列表的大小分配一个新数组。

Java ArrayList示例 (Java ArrayList Example)

Let’s have a look at the ArrayList methods example through some programs.

让我们通过一些程序看一下ArrayList方法示例。

Java ArrayList的常见操作 (Java ArrayList common operations)

Below is a simple program for Arraylist example showing commonly used methods.

下面是一个简单的Arraylist示例程序,显示了常用方法。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Java ArrayList Example Program
 * 
 * @author pankaj
 *
 */
public class ArrayListExample {

	public static void main(String args[]) {
		List<String> letters = new ArrayList<String>();
		
		//add example
		letters.add("A");
		letters.add("C");
		letters.add("D");
		
		//let's insert B between A and C
		letters.add(1,"B");
		System.out.println(letters);
		
		List<String> list = new ArrayList<String>();
		list.add("E");list.add("H");
		
		//appending list elements to letters
		letters.addAll(list);
		System.out.println(letters);
		
		//clear example to empty the list
		list.clear();
		
		list.add("F");list.add("G");
		
		//inserting list inside letters to get right sequence
		letters.addAll(5, list);
		System.out.println(letters);
		
		//contains example
		System.out.println("Letters list contains E ? "+letters.contains("E"));
		System.out.println("Letters list contains Z ? "+letters.contains("Z"));
		
		//ensureCapacity example, it's ArrayList method, so object should be defined like below.
		ArrayList<String> tempList = new ArrayList<>();
		tempList.ensureCapacity(1000);
		
		//get example
		String e = letters.get(4);
		System.out.println("Letter at 5th place: "+e);
		
		//tempList is empty?
		System.out.println("tempList is empty ? "+tempList.isEmpty());
		
		//indexOf example
		System.out.println("First index of D = "+letters.indexOf("D"));
		System.out.println("Last index of D = "+letters.lastIndexOf("D"));
		
		//remove examples
		System.out.println(letters);
		String removed = letters.remove(3);
		System.out.println("After removing '"+removed+"' letters contains "+letters);
		
		//remove first occurrence of H
		boolean isRemoved = letters.remove("H");
		System.out.println("H removed? "+isRemoved+". Letters contains "+letters);
		System.out.println("list contains "+list);
		
		//remove all matching elements between letters and list
		letters.removeAll(list);
		System.out.println(letters);
		
		//retainAll example
		list.clear();list.add("A");list.add("B");list.add("C");
		letters.retainAll(list);
		System.out.println("letters elements after retainAll operation: "+letters);
		
		//size example
		System.out.println("letters ArrayList size = "+letters.size());
		
		//set example
		letters.set(2, "D");
		System.out.println(letters);
		
		//toArray example
		String[] strArray = new String[letters.size()];
		strArray = letters.toArray(strArray);
		System.out.println(Arrays.toString(strArray));
	}
}

Output of above program is given below.

上面程序的输出如下。

[A, B, C, D]
[A, B, C, D, E, H]
[A, B, C, D, E, F, G, H]
Letters list contains E ? true
Letters list contains Z ? false
Letter at 5th place: E
tempList is empty ? true
First index of D = 3
Last index of D = 3
[A, B, C, D, E, F, G, H]
After removing 'D' letters contains [A, B, C, E, F, G, H]
H removed? true. Letters contains [A, B, C, E, F, G]
list contains [F, G]
[A, B, C, E]
letters elements after retainAll operation: [A, B, C]
letters ArrayList size = 3
[A, B, D]
[A, B, D]

Java ArrayList forEach (Java ArrayList forEach)

Java ArrayList forEach method was added in Java 8. It’s useful when you want to perform same action on all the elements. The method argument Consumer is a functional interface, so we can use lambda expressions too. Below is an example of forEach method showing the old school way as well as lambda expression way.

Java 8中添加了Java ArrayList forEach方法。当您要对所有元素执行相同的操作时,此方法很有用。 方法参数Consumer是一个功能接口,因此我们也可以使用lambda表达式。 下面是一个forEach方法的示例,它显示了旧式方法以及lambda表达方法。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ArrayListForEachExample {

	public static void main(String[] args) {
		
		List<String> stocks = new ArrayList<>();
		stocks.add("Google"); stocks.add("Apple");
		stocks.add("Microsoft"); stocks.add("Facebook");
		
		Consumer<Object> consumer = new ArrayListForEachExample().new MyConsumer();
		
		stocks.forEach(consumer);
		
		//lambda style
		stocks.forEach(x -> {System.out.println("Processed "+x);});
		
	}

	class MyConsumer implements Consumer<Object>{

		@Override
		public void accept(Object t) {
			System.out.println("Processing "+t);
		}
		
	}
}

Output produced by ArrayList forEach example program is:

ArrayList forEach示例程序产生的输出为:

Processing Google
Processing Apple
Processing Microsoft
Processing Facebook
Processed Google
Processed Apple
Processed Microsoft
Processed Facebook

Java ArrayList迭代器 (Java ArrayList Iterator)

Iterator is an interface in Java Collections framework. ArrayList provides fail-fast iterator implementation. When you want to perform some operation on all the list elements, you should use Iterator. If any structural modification is made to the list while iterating, it’s next() operation will throw ConcurrentModificationException. Below is a simple example of ArrayList iterator.

Iterator是Java Collections框架中的接口。 ArrayList提供了快速失败的迭代器实现。 要对所有列表元素执行某些操作时,应使用Iterator。 如果在迭代时对列表进行了任何结构修改,则next()操作将抛出ConcurrentModificationException。 以下是ArrayList迭代器的简单示例。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListIteratorExample {

	public static void main(String[] args) {

		List<Integer> ints = new ArrayList<>();
		for(int i=0; i<10; i++) ints.add(i);
		
		Iterator<Integer> it = ints.iterator();
		
		//simple iteration
		while(it.hasNext()){
			int x = (int) it.next();
			System.out.print(x + ", ");
		}
		System.out.println("\n"+ints);
		
		//modification of list through iterator
		it = ints.iterator();
		while(it.hasNext()){
			int x = (int) it.next();
			if(x%2 ==0) it.remove();
		}
		System.out.println(ints);
		
		//changing list structure while iterating
		it = ints.iterator();
		while(it.hasNext()){
			int x = (int) it.next(); //ConcurrentModificationException here
			if(x==5) ints.add(20);
		}
	}

}

Output produced by above ArrayList iterator example program is:

上面的ArrayList迭代器示例程序产生的输出是:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
	at java.util.ArrayList$Itr.next(ArrayList.java:851)
	at com.journaldev.examples.ArrayListIteratorExample.main(ArrayListIteratorExample.java:34)

Read more about ConcurrentModificationException and how to avoid it.

阅读有关ConcurrentModificationException的更多信息以及如何避免它

Java ArrayList ListIterator (Java ArrayList ListIterator)

We can use ListIterator to traverse the list in both the direction. It allows us to remove as well as add an element to the list. You can also get the iterator current position in ListIterator. Let’s have a look at a simple ArrayList ListIterator example for traversing the list backward and modifying the list data.

我们可以使用ListIterator在两个方向上遍历列表。 它允许我们删除元素以及将元素添加到列表中。 您还可以在ListIterator中获得迭代器的当前位置。 让我们看一个简单的ArrayList ListIterator示例,该示例用于向后遍历列表并修改列表数据。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ArrayListListIteratorExample {

	public static void main(String[] args) {

		List<Integer> ints = new ArrayList<>();
		for (int i = 0; i < 10; i++) ints.add(i);
		
		ListIterator<Integer> lit = ints.listIterator(ints.size());
		
		while(lit.hasPrevious()){
			int x = lit.previous();
			System.out.print(x + ", ");
			if(x==5){
				lit.remove();
				lit.add(20);
			}
		}
		System.out.println("\n"+ints);
	}
}

Notice the output produced by the above program.

注意上面程序产生的输出。

9, 8, 7, 6, 5, 20, 4, 3, 2, 1, 0, 
[0, 1, 2, 3, 4, 20, 6, 7, 8, 9]

Java ArrayList removeIf (Java ArrayList removeIf)

ArrayList removeIf method was added in Java 8. This method will remove all of the elements in the list that satisfy the given predicate. Let’s look at a simple program of Java ArrayList removeIf example.

ArrayList removeIf方法是在Java 8中添加的。此方法将删除列表中满足给定谓词的所有元素。 让我们看一个简单的Java ArrayList程序removeIf示例。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class ArrayListRemoveIfExample {

	public static void main(String[] args) {
		List<Integer> ints = new ArrayList<>();
		for (int i = 0; i < 10; i++) ints.add(i);
		
		Predicate<Integer> filter = new ArrayListRemoveIfExample(). new MyPredicate();
		
		ints.removeIf(filter);
		
		System.out.println(ints);
		
		//lambda expression, remove elements divisible by 3
		ints.removeIf(x -> {return x %3 == 0;});
		
		System.out.println(ints);
	}

	class MyPredicate implements Predicate<Integer> {

		@Override
		public boolean test(Integer t) {
			return t %2 == 0;
		}
		
	}
}

Below is the output of above program.

下面是上面程序的输出。

[1, 3, 5, 7, 9]
[1, 5, 7]

Java ArrayList replaceAll (Java ArrayList replaceAll)

ArrayList replaceAll method was added in Java 8. It’s useful when you want to apply some function on all the elements of the list. Let’s have a look at ArrayList replaceAll example program.

ArrayList replaceAll方法是在Java 8中添加的。当您要对列表的所有元素应用某些功能时,此方法很有用。 让我们看一下ArrayList replaceAll示例程序。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

public class ArrayListReplaceAllExample {

	public static void main(String[] args) {
		List<Integer> ints = new ArrayList<>();
		for (int i = 0; i < 10; i++) ints.add(i);
		
		//multiply all elements by 10
		UnaryOperator<Integer> operator = new ArrayListReplaceAllExample(). new MyUnaryOperator();
		ints.replaceAll(operator);
		System.out.println(ints);
		
		//lambda expression example, multiply by 5
		ints.replaceAll(x -> {return x*5;});
		System.out.println(ints);
	}

	class MyUnaryOperator implements UnaryOperator<Integer>{

		@Override
		public Integer apply(Integer t) {
			return t*10;
		}
		
	}
}

Below is the output of above replaceAll example program.

以下是上述replaceAll示例程序的输出。

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]

Java ArrayList子列表 (Java ArrayList subList)

When we use subList method with a list, it returns the view of a portion of the original list. This new list is backed by the original list, so any modifications will reflect to other list too. The semantics of the list returned by this method become undefined if the backing list is structurally modified in any way other than via the returned list. All methods on the new list first check to see if the actual modCount of the backing list is equal to its expected value, and throw a ConcurrentModificationException if it is not. Let’s see this behaviour with a simple ArrayList subList example.

当我们对列表使用subList方法时,它返回原始列表一部分的视图。 此新列表由原始列表支持,因此任何修改也将反映到其他列表。 如果以非通过返回列表的方式对后备列表进行结构上的修改,则此方法返回的列表的语义将变得不确定。 新列表上的所有方法首先检查后备列表的实际modCount是否等于其期望值,如果不相等,则抛出ConcurrentModificationException。 让我们用一个简单的ArrayList subList示例查看此行为。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSubListExample {

	public static void main(String[] args) {
		
		List<String> names = new ArrayList<>();
		names.add("Pankaj"); names.add("David");names.add("Lisa");names.add("Meghna");
		
		List<String> first2Names = names.subList(0, 2);
		
		System.out.println(names +" , "+first2Names);
		
		names.set(1, "Kumar");
		//check the output below. :)
		System.out.println(names +" , "+first2Names);
		
		first2Names.add("Megan"); //this is fine
		System.out.println(names +" , "+first2Names); //this is fine
		
		//Let's modify the list size and get ConcurrentModificationException
		names.add("Deepak");
		System.out.println(names +" , "+first2Names); //this line throws exception

	}

}

Below is the output of above ArrayList subList example program.

下面是上面的ArrayList subList示例程序的输出。

[Pankaj, David, Lisa, Meghna] , [Pankaj, David]
[Pankaj, Kumar, Lisa, Meghna] , [Pankaj, Kumar]
[Pankaj, Kumar, Megan, Lisa, Meghna] , [Pankaj, Kumar, Megan]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1231)
	at java.util.ArrayList$SubList.listIterator(ArrayList.java:1091)
	at java.util.AbstractList.listIterator(AbstractList.java:299)
	at java.util.ArrayList$SubList.iterator(ArrayList.java:1087)
	at java.util.AbstractCollection.toString(AbstractCollection.java:454)
	at java.lang.String.valueOf(String.java:2994)
	at java.lang.StringBuilder.append(StringBuilder.java:131)
	at com.journaldev.examples.ArrayListSubListExample.main(ArrayListSubListExample.java:26)

Java ArrayList排序 (Java ArrayList Sorting)

We can use ArrayList sort method for sorting it’s elements. Below is a simple example showing ArrayList sorting.

我们可以使用ArrayList排序方法对其元素进行排序。 以下是显示ArrayList排序的简单示例。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class ArrayListSortingExample {

	public static void main(String[] args) {
		List<Integer> ints = new ArrayList<>();
		Random random = new Random();
		for (int i = 0; i < 10; i++) ints.add(random.nextInt(1000));
		
		System.out.println("Original List: "+ints);
		
		//sort the list
		MyComparator c = new ArrayListSortingExample(). new MyComparator();
		ints.sort(c);
		System.out.println("Sorted in Increasing Order: "+ints);
		
		//lambda example, sort in reverse order
		ints.sort((o1,o2) -> {return (o2-o1);});
		System.out.println("Sorted in Decreasing Order: "+ints);
		
	}
	
	class MyComparator implements Comparator<Integer>{
		@Override
		public int compare(Integer o1, Integer o2) {
			return (o1 - o2);
		}	
	}
}

Output of above sorting program is:

上述排序程序的输出为:

Original List: [580, 855, 889, 858, 536, 842, 223, 405, 854, 354]
Sorted in Increasing Order: [223, 354, 405, 536, 580, 842, 854, 855, 858, 889]
Sorted in Decreasing Order: [889, 858, 855, 854, 842, 580, 536, 405, 354, 223]

线程安全ArrayList (Thread Safe ArrayList)

Java ArrayList is not thread-safe. So if you are working in a multi-threaded environment, use below code to get thread-safe ArrayList.

Java ArrayList不是线程安全的。 因此,如果您在多线程环境中工作,请使用以下代码获取线程安全的ArrayList。

List<Integer> synchronizedList = Collections.synchronizedList(ints);

You can also use CopyOnWriteArrayList concurrent collection class in this case.

在这种情况下,您还可以使用CopyOnWriteArrayList并发集合类。

That’s all for Java ArrayList example tutorial, I hope nothing important got missed here. 🙂

这就是Java ArrayList示例教程的全部内容,我希望这里没有重要的内容。 🙂

翻译自: https://www.journaldev.com/11404/java-arraylist

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值