ArrayList 与 List 关系与代码示例 - Java
Posted klchang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
public interface List<E>
extends Collection<E>
An ordered collection (also known as a sequence).
java.util
Class ArrayList<E>
- java.lang.Object
- java.util.AbstractCollection<E>
- java.util.AbstractList<E>
- java.util.ArrayList<E>
- java.util.AbstractList<E>
- java.util.AbstractCollection<E>
All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
Direct Known Subclasses:
AttributeList, RoleList, RoleUnresolvedList
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
以上是关于ArrayList 与 List 关系与代码示例 - Java的主要内容,如果未能解决你的问题,请参考以下文章
Java中请说明集合类ArrayList与 HashMap的区别?