java.util.ArrayList<E>
从书中各种代码来看,java.util.ArrayList<E>
是非常重要的一个类,在代码中广泛使用,E
表示泛型,ArrayList
是一个泛型类。
ArrayList
相当于C++ 的vector
,用于存储对象。与数组不同,数组一旦创建,长度固定,但是ArrayList
的长度是动态的,不受限制,可以存储任意多的对象,但是只能存储对象,不能存储原生数据类型例如int
。
java.util.ArrayList < E > 的一些方法 | 描述 |
---|---|
+ArrayList() | 构造函数,创建一个空的列表, size为0 |
+add(o: E): void | 在list的末尾添加一个元素o |
+add(index: int, o: E): void | 在指定的index处插入元素o |
+clear(): void | 从list中删除所有元素 |
+contains(o: Object): boolean | 如果list含有元素o,返回true |
+get(index: int): E | 返回指定index处的元素 |
+indexOf(o: Object): int | 返回list中第一个匹配元素的index |
+isEmpty(): boolean | 如果list不含元素,返回true |
+lastIndexOf(o: Object): int | 返回list中最后一个匹配元素的index |
+remove(o: Object): boolean | 删除list中的第一个元素o,如果元素被删除,返回true |
+size(): int | 返回list中元素个数 |
+remove(index: int): boolean | 删除指定index处的元素,如果元素被删除,返回true |
+set(index: int, o: E): E | 设置指定index处的元素为o |
数组和ArrayList
的比较
操作 | Array | ArrayList |
---|---|---|
创建 array/ArrayList | String[] a = new String[10] | ArrayList list = new ArrayList<>(); |
访问一个元素 | a[index] | list.get(index); |
更新一个元素 | a[index] = “London”; | list.set(index, “London”); |
返回大小 | a.length | list.size(); |
排序 | java.util.Arrays.sort(array) | java.util.Collections.sort(arraylist) |
添加一个新元素 | 相当复杂 | list.add(“London”); |
插入一个新元素 | 相当复杂 | list.add(index, “London”); |
删除一个元素 | 相当复杂 | list.remove(index); |
删除一个元素 | 相当复杂 | list.remove(Object); |
删除所有元素 | ? | list.clear(); |
创建一个存储字符串的ArrayList对象:
ArrayList<String> cities = new ArrayList<String>();
创建一个存储日期的ArrayList对象:
ArrayList<java.util.Date> dates = new ArrayList<java.util.Date> ();
JDK 7 之后,下述表达式
ArrayList<AConcreteType> list = new ArrayList<AConcreteType>();
可以简化为:
ArrayList<AConcreteType> list = new ArrayList<>();
因为编译器有一个新的feature叫做类型推断(type inference), 能够从变量声明推断类型。
例1
import java.util.ArrayList;
public class TestArrayList {
public static void main(String[] args) {
// Create a list to store cities
ArrayList<String> cityList = new ArrayList<String>();
// Add some cities in the list
cityList.add("London");
// cityList now contains [London]
cityList.add("Denver");
// cityList now contains [London, Denver]
cityList.add("Paris");
// cityList now contains [London, Denver, Paris]
cityList.add("Miami");
// cityList now contains [London, Denver, Paris, Miami]
cityList.add("Seoul");
// Contains [London, Denver, Paris, Miami, Seoul]
cityList.add("Tokyo");
// Contains [London, Denver, Paris, Miami, Seoul, Tokyo]
System.out.println("List size? " + cityList.size()); // 6
System.out.println("Is Miami in the list? " + cityList.contains("Miami")); // true
System.out.println("The location of Denver in the list? " + cityList.indexOf("Denver")); // 1 返回索引,如果不在list中,返回-1
System.out.println("Is the list empty? " + cityList.isEmpty()); // Print false
// Insert a new city at index 2
cityList.add(2, "Xian");
// Contains [London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
// Remove a city from the list
cityList.remove("Miami");
// Contains [London, Denver, Xian, Paris, Seoul, Tokyo]
// Remove a city at index 1
cityList.remove(1);
// Contains [London, Xian, Paris, Seoul, Tokyo]
// Display the contents in the list
System.out.println(cityList.toString());
// Display the contents in the list in reverse order
for (int i = cityList.size() - 1; i >= 0; i--)
System.out.print(cityList.get(i) + " ");
System.out.println();
// Create a list to store two circles
ArrayList<CircleFromSimpleGeometricObject> list = new ArrayList<CircleFromSimpleGeometricObject>();
// Add two circles
list.add(new CircleFromSimpleGeometricObject(2));
list.add(new CircleFromSimpleGeometricObject(3));
// Display the area of the first circle in the list
System.out.println("The area of the circle? " + list.get(0).getArea());
}
}
其中System.out.println(cityList.toString());
等同于 System.out.println(cityList);
toString()
方法返回列表的字符串表示,形式为 [e0.toString(), e1.toString(), ..., ek.toString()]
,e0, e1, . . . ,
和 ek
都是列表中的元素。
由于ArrayList只能存储对象,不能存储原生数据类型数据,下面的代码是错误的:
ArrayList<int> list = new ArrayList<>();
错误!!!!!
只能写成:
ArrayList<Integer> list = new ArrayList<>();
例2
用户输入一个数字序列,假定输入以0
结尾,且0
不计入数字序列,打印序列中不重复的数字:
package TEST_ALL;
import java.util.ArrayList;
import java.util.Scanner;
public class DistinctNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
System.out.print("Enter integers (input ends with 0): ");
int value;
do {
value = input.nextInt(); // Read a value from the input
if (!list.contains(value) && value != 0)
list.add(value); // Add the value if it is not in the list
} while (value != 0);
// Display the distinct numbers
for (int i = 0; i < list.size(); i++)
System.out.print(list.get(i) + " ");
}
}
运行结果:
Enter integers (input ends with 0): 2 32 3 1 2 3 2 9 0
2 32 3 1 9
可以用下列 foreach 循环遍历一个array list:
for (elementType element: arrayList) {
// Process the element
}
例如上例中的语句:
for (int i = 0; i < list.size(); i++)
System.out.print(list.get(i) + " ");
可以改写为:
for (int number: list)
System.out.print(number + " ");
书后的练习
我做的答案:
11.30 How do you do the following?
a. Create an ArrayList for storing double values?
ArrayList<Double> list_double = new ArrayList<Double>();`
b. Append an object to a list?
Double o = new Double(11);
list_double.add(o);
c. Insert an object at the beginning of a list?
Double o = new Double(11);
list_double.add(0, o);
d. Find the number of objects in a list?
list_double.size();
e. Remove a given object from a list?
Double o = new Double(11);
while(list_double.contains(o))
list_double.remove(o);
f. Remove the last object from the list?
list_double.remove(list_double.size() - 1);
g. Check whether a given object is in a list?
Double o = new Double(11);
if (list_double.contains(o))
System.out.print("Y");
else
System.out.print("N");
h. Retrieve an object at a specified index from a list?
int index = 111;
list_double.get(index);
11.31 Identify the errors in the following code.
ArrayList<String> list = new ArrayList<>();
list.add("Denver");
list.add("Austin");
list.add(new java.util.Date()); # 错误,元素数据类型必须一致,不能改成Date
String city = list.get(0);
list.set(3, "Dallas"); #
System.out.println(list.get(3)); # 错误,index 超出 size
list.set(3, "Dallas")
; 和list.get(3)
都是错的,You cannot use the get(index)
and set(index, element)
methods if the element is not in the list. 看源代码,get
和 set
都有RangeCheck(index);
这个函数:
private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
}
11.32 Suppose the ArrayList list
contains {"Dallas", "Dallas", "Houston", "Dallas"}
.What is the list
after invoking list.remove("Dallas")
one time?
Does the following code correctly remove all elements with value "Dallas"
from
the list
? If not, correct the code.
for (int i = 0; i < list.size(); i++)
list.remove("Dallas");
调用一次list.remove("Dallas")
, list
变为 { "Dallas", "Houston", "Dallas"}
,
code不能完全删除 "Dallas"
,因为最后结果是{"House", "Dallas"}
, 应该改成:
while(list.contains("Dallas"))
list.remove("Dallas");
11.33 Explain why the following code displays [1, 3] rather than [2, 3].
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.remove(1);
System.out.println(list);
因为remove
方法有两种签名:list.remove(Object)
,list.remove(index)
; 此处调用的是第二种,如果要删除第一个元素,必须改成list.remove((Integer)1)
.
(这里不是特别理解)
11.34 Explain why the following code is wrong.
ArrayList<Double> list = new ArrayList<>();
list.add(1);
错误是因为, 1
为整型,与 Double
类型不符,必须改成 1.0
.
也不能改为list.add((Double)1)
, 否则会显示 inconvertible type 的错误.
[1] Introduction to Java Programming 10th edition Chapter 11.11