java.util.ArrayList<E>
allows for expandable arrays,
and is basically the same as the older the Collections Vector class.
An ArrayList has these characteristics:
- An ArrayList automatically expands as data is added.
- Access to any element of an ArrayList is O(1). Insertions and deletions are O(N).
- An ArrayList has methods for inserting, deleting, and searching.
- An ArrayList can be traversed using a foreach
loop, iterators, or indexes.
Arrays or ArrayList?
Programmers are frequently faced with the choice of using a simple array or
an ArrayList. If the data has a known number of elements or small fixed
size upper bound, or where efficiency in using primitive types is important,
arrays are often the best choice. However, many data storage problems
are not that simple, and ArrayList (or one of the other Collections classes)
might be the right choice.
Automatic expansion.
Use ArrayList when there will be a large variation in the amount
of data that you would put into an array. Arrays should be used only when there
is a constant amount of data. For example, storing information
about the days of the week should use an array because the number of
days in a week is constant. Use an array list for your email contact
list because there is no upper bound on the number of contacts.
Objects only.
A possible disadvantage of ArrayList is that it
holds only object types and not primitive types (eg, int
).
To use a primitive type in an ArrayList,
put it inside an object or use of the wrapper
classes (eg, Integer, Double, Character, ...).
The wrapper classes are immutable
, so
if you use, eg, Integer,
you will not be able to change the integer value.
In this case it may be more useful to define your own mutable class.
Implementation.
ArrayLists are implemented with an underlying array,
and when that array is full and an additional element
is added, a new, larger, array is allocated and the elements are copied from the old to the new.
Because
it takes time to create a bigger array and copy the
elements from the old array to the new array, it is a slightly faster
to create an ArrayList with a size that it will commonly be when full. Of course, if you knew the
final size, you could simply use an array. However, for non-critical sections of code
programmers typically don't specify an initial size.
Common ArrayList methods and constructors
Here are some of the most useful ArrayList methods. Assume these declarations.
Note that E
is the notation for the type of an element
in a collection.
Sun recommends using single upper case letters for generic types.
int i;
ArrayList<E> a;
E e;
Iterator<E> iter;
ListIterator<E> liter;
E[] earray;
Object[] oarray;
Result
Method
Description
a
=
|
new ArrayList<E>()
|
Creates ArrayList with initial default capacity 10. |
a
=
|
new ArrayList<E>(cap
)
|
Creates ArrayList with initial int capacity cap
. |
a
=
|
newArrayList<E>(coll<E>
)
|
Creates ArrayList from the Collection
coll
. |
|
a
.add
(e
)
|
adds e
to end of ArrayList a
|
|
a
.add(i
, e
)
|
Inserts e
at index i
, shifting elements up as necessary. |
|
a
.set(i
,e
)
|
Sets the element at index i
to e
. |
e
=
|
a
.get
(i)
|
Returns the object at index i
. |
oarray
=
|
a
.toArray
()
|
Returns values in array of objects. |
earray
=
|
a
.toArray
(E[])
|
The array parameter should be of the E class.
Returns values in that array (or a larger
array is allocated if necessary). |
iter
=
|
a
.iterator
()
|
Returns an Iterator for forward traversal. |
liter
=
|
a
.listIterator
(i
)
|
Returns a ListIterator for forward / backward / modifying traversal, starting at index i
.
Start from end with a.listIterator(a.size())
|
liter
=
|
a
.listIterator
()
|
Returns a ListIterator for forward / backward / modifying traversal. |
b
=
|
a
.contains(e
)
|
Returns true if ArrayList a
contains e
|
i
=
|
a
.indexOf(e
)
|
Returns index of first occurrence of e
, or -1 if not there. |
i
=
|
a
.lastIndexOf(e
)
|
Returns index of last occurrence of e
, or -1 if not there. |
|
a
.clear()
|
removes all elements from ArrayList a
|
|
a
.remove(i
)
|
Removes the element at position i
. |
|
a
.removeRange(i
, j
)
|
Removes the elements from positions i
thru j
. |
i
=
|
a
.size
()
|
Returns the number of elements in ArrayList a
. |
Adding elements to the end of an ArrayList, getting them by index
ArrayList<E> a = new ArrayList<E>(); // Default size.
E s; // Declare s to be an object type E.
. . .
a.add(s); // Adds s to the end of the ArrayList a
. . .
s = a.get(i); // Assigns ith element from a to s.
To get successive elements from an ArrayList - Four ways
Use either a for
loop with an integer index to get all the elements from an ArrayList,
or go over all elements in a ArrayList using an Iterator (forward) or ListIterator (forward / backward).
-
foreach
loop
. This is fast and works for all kinds of lists,
but is not entirely flexible (only sequential forward with no deletions,
additions, or multiple references). This should be your first choice
in programming.
Works efficiently with both ArrayList and LinkedList.
ArrayList<String> a = new ArrayList<String>();
. . .
for (String s : a) {
System.out.println(s);
}
-
for
loop with index
. This is fast, but should not be
used with a LinkedList.
It does allow orders other than sequentially forward by one.
for (int i = 0; i < a.size(); i++) {
System.out.println(a.get(i));
}
-
Iterator<E>
- Allows simple forward traversal. Can be used for the largest number of other
kinds of data structures.
This example uses an Iterator to print all elements (Strings) in an ArrayList.
It uses hasNext()
,
which returns true if there are more elements, and
next()
, which returns the next element.
Works with both ArrayList and LinkedList.
for (Iterator<String> iter = a.iterator(); iter.hasNext(); ) {
System.out.println(iter.next());
}
-
ListIterator<E>
- Allows traversal of the ArrayList,
but it is more general than a simple Iterator, allowing inserts and deletes
(although both are very slow for an ArrayList). It also allows bidirectional traversal.
Works efficiently with both ArrayList and LinkedList.
Sorting
If the data in your ArrayList has a natural sorting order
(ie, implements Comparable
, as do String, Integer, ...),
you can simply call the static Collections.sort()
method.
This is a stable, guaranteed n log n sort.
Collections.sort(yourArrayList
);
If you want to choose a different sort criterion or
your data doesn't implement xxxx, you will have to define
a Comparator and pass that to the sort() method.
Collections.sort(yourArrayList
, yourComparator
);
Check out Collections for other useful utility methods.
分享到:
相关推荐
深入Java集合学习系列(二): ArrayList实现原理
Java试题-2:ArrayList类动态代理 什么是动态代理 动态代理该怎么实现
深入Java集合学习系列(三): ArrayList实现原理
源码解析jdk7.0集合:ArrayList的底层实现原理.pdf
jdk源码阅读一:ArrayList
·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...
NULL 博文链接:https://zhangshixi.iteye.com/blog/674856
学生管理系统 分别三种方法控制台实现: ArrayList、SQL语句、存储过程
本实例主要是对Android移动开发中的ArrayList的初步学习,涉及到HashMap的使用,以及为ArrayList添加监听器,还涉及到Toast的简单应用。
·基于JDK 11,将Java8、Java9、Java10、Java11新特性一网打尽 ·课程中,Eclipse和IDEA这两种企业一线开发环境都使用到了 3.技术讲解更深入、更全面: ·课程共30天,715个知识视频小节,涉及主流Java使用的...
java lru leetcode Java笔记 我在工作和学术期间写的 Java 注释和备忘单 通用Java HashMap 与 TreeMap HashMap : the hash map we know TreeMap : maintain a red - black tree internally, not O( 1 ) lookup, but ...
java软件技术文档
import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; /** * @Author Ziph * @date 2020/2/19 * @Email mylifes1110@163.com */ public class TestDemo implemen
java中对ArrayList进行排序的方法参考
java中ArrayList的用法
1.长 增加add,查看下表,遍历,删除值,下标,数组,改下标付值, 度是可变的 length:长度 capacity:容量,capacity不能小于实际内容的值,当你将length变大之后,capacity会自动变大。 2.它的类型是object,---...
java数据结构 ArrayList、Stack、Map,为提高效率,未做边界判断(由开发人员保证逻辑上不会出现越界),实现了添加和查询的功能,无修改删除功能
java8 源码 List相关实现类的源码解析(JDK1.8) 2018.9.22- List的架构图 ArrayList 继承关系: ArrayList -> AbstractList 实现 List接口 ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的...
1) 掌握Java集合框架的概念以及几种具体实现:ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue; 2) 掌握Java集合框架的映射的概念以及映射的两种基本实现:HashMap,TreeMap; 3)掌握枚举类型以及枚举集...