当前位置:   article > 正文

[Java] ArrayList 类_arraylist list = new arraylist<>();

arraylist list = new arraylist<>();

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的比较

操作ArrayArrayList
创建 array/ArrayListString[] a = new String[10]ArrayList list = new ArrayList<>();
访问一个元素a[index]list.get(index);
更新一个元素a[index] = “London”;list.set(index, “London”);
返回大小a.lengthlist.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>();
  • 1

创建一个存储日期的ArrayList对象:

ArrayList<java.util.Date> dates = new ArrayList<java.util.Date> ();
  • 1

JDK 7 之后,下述表达式

ArrayList<AConcreteType> list = new ArrayList<AConcreteType>();
  • 1

可以简化为:

ArrayList<AConcreteType> list = new ArrayList<>();
  • 1

因为编译器有一个新的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());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

其中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) + " ");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

运行结果:

Enter integers (input ends with 0): 2 32 3 1 2 3 2 9 0
2 32 3 1 9 
  • 1
  • 2

可以用下列 foreach 循环遍历一个array list:

for (elementType element: arrayList) {
	// Process the element 
}
  • 1
  • 2
  • 3

例如上例中的语句:

for (int i = 0; i < list.size(); i++)
    System.out.print(list.get(i) + " ");
  • 1
  • 2

可以改写为:

for (int number: list)
    System.out.print(number + " ");
  • 1
  • 2

书后的练习

我做的答案:

11.30 How do you do the following?

a. Create an ArrayList for storing double values?

ArrayList<Double> list_double = new ArrayList<Double>();`
  • 1

b. Append an object to a list?

Double o = new Double(11);
list_double.add(o);
  • 1
  • 2

c. Insert an object at the beginning of a list?

Double o = new Double(11);
list_double.add(0, o);
  • 1
  • 2

d. Find the number of objects in a list?

list_double.size();
  • 1

e. Remove a given object from a list?

Double o = new Double(11);
while(list_double.contains(o))
    list_double.remove(o);
  • 1
  • 2
  • 3

f. Remove the last object from the list?

list_double.remove(list_double.size() - 1);
  • 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");
  • 1
  • 2
  • 3
  • 4
  • 5

h. Retrieve an object at a specified index from a list?

int index = 111;
list_double.get(index);
  • 1
  • 2

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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. 看源代码,getset 都有RangeCheck(index); 这个函数:

private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
}
  • 1
  • 2
  • 3
  • 4

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");
  • 1
  • 2

调用一次list.remove("Dallas")list 变为 { "Dallas", "Houston", "Dallas"}
code不能完全删除 "Dallas",因为最后结果是{"House", "Dallas"}, 应该改成:

while(list.contains("Dallas"))
    list.remove("Dallas");
  • 1
  • 2

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

因为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
  • 2

错误是因为, 1 为整型,与 Double 类型不符,必须改成 1.0.
也不能改为list.add((Double)1), 否则会显示 inconvertible type 的错误.


[1] Introduction to Java Programming 10th edition Chapter 11.11

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/77302
推荐阅读
相关标签
  

闽ICP备14008679号