ArrayList 与 List 关系与代码示例 - Java

关系

List 是 Java Interface, ArrayList 是 Java Class,它们都属于 java.util 包。

Java List 是有序的集合(ordered collection),也称为序列(Sequence);

Java ArrayList 是 Java List Interface 的可变大小的数组实现。

这两者在 JAVA collection framework 位置,如下图所示:

再来看看官方文档说明:

java.util

Interface List<E>

  • Type Parameters:

E - the type of elements in this list

All Superinterfaces:

Collection<E>, Iterable<E>

All Known Implementing Classes:

AbstractListAbstractSequentialListArrayListAttributeListCopyOnWriteArrayListLinkedListRoleListRoleUnresolvedListStackVector


public interface List<E>

extends Collection<E>

An ordered collection (also known as a sequence).

 

java.util

Class ArrayList<E>

All Implemented Interfaces:

SerializableCloneableIterable<E>, Collection<E>, List<E>, RandomAccess

Direct Known Subclasses:

AttributeListRoleListRoleUnresolvedList


public class ArrayList<E>

extends AbstractList<E>

implements List<E>, RandomAccess, Cloneable, Serializable

Resizable-array implementation of the List interface.

 

示例

1. 新建一个 ArrayList 对象

List<String> brands = new ArrayList<String>();

2. 向其中增加元素

brands.add("Jack Amber");

3. 完整示例

// BeerExpert.java, excerpted from Dawn Griffiths & David Griffiths, "Head First Android Development",  2015
import java.util.ArrayList;
import java.util.List;

public class BeerExpert {
    List<String> getBrands (String color) {
        List<String> brands = new ArrayList<String>();
        if (color.equals("amber")) {
            brands.add("Jack Amber");
            brands.add("Red Moose");
        } else {
            brands.add("Jail Pale Ale");
            brands.add("Gout Stout");
        }
        
        return brands;
    }
}

 

参考资料

[1] Oracle Corporation. Class ArrayList<E> - Java™ Platform Standard Ed. 8 [OL]. https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html

[2] Oracle Corporation. Interface List<E> - Java™ Platform Standard Ed. 8 [OL]. https://docs.oracle.com/javase/8/docs/api/java/util/List.html

[3] Stack Overflow Users. Type List vs type ArrayList in Java [OL]. https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java

 

posted @ 2017-12-02 16:24  klchang  阅读(1808)  评论(0编辑  收藏  举报