Java集合框架学习(五) ArrayList详解
Arraylist介绍
Arraylist类实现了List接口。
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
它可以存放任何元素,包括重复元素,包括多个null值。
因为其功能性和灵活性而被广泛使用。
绝大多数开发者选择ArrayList来替代Array,因为其很好的伸缩性。
因为数组的长度是固定的,并且在删除元素后其所占空间并不会回收。
而ArrayList则相反,长度是随元素大小动态收缩的。
入门例子
package com.dylan.collection;
import java.util.ArrayList;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class ArrayListExample {
public static void main(String args[]) {
/*Creation of ArrayList: I'm going to add String
*elements so I made it of string type */
ArrayList<String> obj = new ArrayList<String>();
/*This is how elements should be added to the array list*/
obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");
/* Displaying array list elements */
System.out.println("Currently the array list has following elements:"+obj);
/*Add element at the given index*/
obj.add(0, "Rahul");
obj.add(1, "Justin");
/*Remove elements from array list like this*/
obj.remove("Chaitanya");
obj.remove("Harry");
System.out.println("Current array list is:"+obj);
/*Remove element from the given index*/
obj.remove(1);
System.out.println("Current array list is:"+obj);
}
}
Currently the array list has following elements:[Ajeet, Harry, Chaitanya, Steve, Anuj]
Current array list is:[Rahul, Justin, Ajeet, Steve, Anuj]
Current array list is:[Rahul, Ajeet, Steve, Anuj]
Arraylist常用方法
1) add( Object o): 添加元素
obj.add("hello");
2) add(int index, Object o): 在指定位置添加元素,位置从0开始计算
obj.add(2, "bye");
3) remove(Object o): 删除元素
obj.remove("Chaitanya");
4) remove(int index): 删除指定位置上的元素
obj.remove(3);
5) set(int index, Object o): 使用指定元素替代指定位置上的元素
obj.set(2, "Tom");
6) int indexOf(Object o): 找到指定元素的位置(下标),找不到返回-1
int pos = obj.indexOf("Tom");
7) Object get(int index): 返回指定位置上的元素
String str= obj.get(2);
8) int size(): 获得ArrayList的大小,即元素的个数
int numberofitems = obj.size();
9) boolean contains(Object o): 判断是否包含指定元素,包含返回true,不包含返回false
obj.contains("Steve");
10) clear(): 清空ArrayList,即删除其中所有元素
obj.clear();
初始化ArrayList方法
1.使用Arrays.asList
ArrayList<Type> obj = new ArrayList<Type>(
Arrays.asList(Object o1, Object o2, Object o3, ....so on));
package com.dylan.collection;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class InitializeArrayListExample1 {
public static void main(String args[]) {
ArrayList<String> obj = new ArrayList<String>(
Arrays.asList("Pratap", "Peter", "Harsh"));
System.out.println("Elements are:"+obj);
}
}
2.使用匿名内部类
ArrayList<T> obj = new ArrayList<T>(){{
add(Object o1);
add(Object o2);
add(Object o3);
...
...
}};
package com.dylan.collection;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class InitializeArrayListExample2 {
public static void main(String args[]) {
ArrayList<String> cities = new ArrayList<String>(){{
add("Delhi");
add("Agra");
add("Chennai");
}};
System.out.println("Content of Array list cities:"+cities);
}
}
3.正常方式
ArrayList<T> obj = new ArrayList<T>();
obj.add("Object o1");
obj.add("Object o2");
obj.add("Object o3");
...
...
package com.dylan.collection;
import java.util.ArrayList;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class InitializeArrayListExample3 {
public static void main(String args[]) {
ArrayList<String> books = new ArrayList<String>();
books.add("Java Book1");
books.add("Java Book2");
books.add("Java Book3");
System.out.println("Books stored in array list are: "+books);
}
}
4.使用Collections.nocopies
ArrayList<T> obj = new ArrayList<T>(Collections.nCopies(count, element));
package com.dylan.collection;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class InitializeArrayListExample4 {
public static void main(String args[]) {
ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5));
System.out.println("ArrayList items: "+intlist);
}
}
遍历ArrayList方法
1.For Loop
2.Advanced for loop
3.While Loop
4.Iterator
5.Enumeration
package com.dylan.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class LoopArrayListExample {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Jack");
arrayList.add("Tom");
arrayList.add("Lucy");
arrayList.add("Brant");
/* For Loop for iterating ArrayList */
System.out.println("For Loop");
for (int counter = 0; counter < arrayList.size(); counter++) {
System.out.println(arrayList.get(counter));
}
/* Advanced For Loop*/
System.out.println("Advanced For Loop");
for (String str : arrayList) {
System.out.println(str);
}
/* While Loop for iterating ArrayList*/
System.out.println("While Loop");
int count = 0;
while (arrayList.size() > count) {
System.out.println(arrayList.get(count));
count++;
}
/*Looping Array List using Iterator*/
System.out.println("Iterator");
Iterator iter = arrayList.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
/*using Enumeration*/
// Get the Enumeration object
Enumeration<String> e = Collections.enumeration(arrayList);
// Enumerate through the ArrayList elements
System.out.println("Enumeration: ");
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
其他常见操作
1.ArrayList排序
1)升序
2)降序Collections.sort(arrayList);
Collections.sort(arrayList, Collections.reverseOrder());
或
Collections.sort(arrayList);
Collections.reverse(arrayList);
3)排序对象ArrayList
package com.dylan.collection;
import java.util.Comparator;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class Student implements Comparable<Student> {
private String studentname;
private int rollno;
private int studentage;
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getStudentage() {
return studentage;
}
public void setStudentage(int studentage) {
this.studentage = studentage;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
@Override
public String toString() {
return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
}
@Override
public int compareTo(Student comparestu) {
int compareage=((Student)comparestu).getStudentage();
/* For Ascending order*/
return this.studentage-compareage;
}
}
package com.dylan.collection;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author xusucheng
* @create 2018-01-28
**/
public class ArrayListSorting {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(223, "Chaitanya", 26));
arraylist.add(new Student(245, "Rahul", 24));
arraylist.add(new Student(209, "Ajeet", 32));
Collections.sort(arraylist);
for(Student str: arraylist){
System.out.println(str);
}
}
}
[ rollno=245, name=Rahul, age=24]
[ rollno=223, name=Chaitanya, age=26]
[ rollno=209, name=Ajeet, age=32]
如果需要更高级的比较策略,请使用:Comparator
import java.util.Comparator;
public class Student {
private String studentname;
private int rollno;
private int studentage;
public Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
...
//Getter and setter methods same as the above examples
...
/*Comparator for sorting the list by Student Name*/
public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
public int compare(Student s1, Student s2) {
String StudentName1 = s1.getStudentname().toUpperCase();
String StudentName2 = s2.getStudentname().toUpperCase();
//ascending order
return StudentName1.compareTo(StudentName2);
//descending order
//return StudentName2.compareTo(StudentName1);
}};
/*Comparator for sorting the list by roll no*/
public static Comparator<Student> StuRollno = new Comparator<Student>() {
public int compare(Student s1, Student s2) {
int rollno1 = s1.getRollno();
int rollno2 = s2.getRollno();
/*For ascending order*/
return rollno1-rollno2;
/*For descending order*/
//rollno2-rollno1;
}};
@Override
public String toString() {
return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
}
}
import java.util.*;
public class Details {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(101, "Zues", 26));
arraylist.add(new Student(505, "Abey", 24));
arraylist.add(new Student(809, "Vignesh", 32));
/*Sorting based on Student Name*/
System.out.println("Student Name Sorting:");
Collections.sort(arraylist, Student.StuNameComparator);
for(Student str: arraylist){
System.out.println(str);
}
/* Sorting on Rollno property*/
System.out.println("RollNum Sorting:");
Collections.sort(arraylist, Student.StuRollno);
for(Student str: arraylist){
System.out.println(str);
}
}
}
Student Name Sorting:
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
[ rollno=101, name=Zues, age=26]
RollNum Sorting:
[ rollno=101, name=Zues, age=26]
[ rollno=505, name=Abey, age=24]
[ rollno=809, name=Vignesh, age=32]
2.将一个ArrayList所有元素插入到另一个ArrayList中(addAll)
import java.util.ArrayList;
public class ExampleOfaddAll {
public static void main(String[] args) {
// ArrayList1 of String type
ArrayList<String> al = new ArrayList<String>();
al.add("Hi");
al.add("hello");
al.add("String");
al.add("Test");
System.out.println("ArrayList1 before addAll:"+al);
//ArrayList2 of String Type
ArrayList<String> al2 = new ArrayList<String>();
al2.add("Text1");
al2.add("Text2");
al2.add("Text3");
al2.add("Text4");
//Adding ArrayList2 into ArrayList1
al.addAll(al2);
System.out.println("ArrayList1 after addAll:"+al);
}
}
或是插入到指定位置:
import java.util.ArrayList;
public class ExampleOfaddAllMethod {
public static void main(String[] args) {
// ArrayList1
ArrayList<String> al = new ArrayList<String>();
al.add("Apple");
al.add("Orange");
al.add("Grapes");
al.add("Mango");
System.out.println("ArrayList1 before addAll:"+al);
//ArrayList2
ArrayList<String> al2 = new ArrayList<String>();
al2.add("Fig");
al2.add("Pear");
al2.add("Banana");
al2.add("Guava");
System.out.println("ArrayList2 content:"+al2);
//Adding ArrayList2 in ArrayList1 at 3rd position(index =2)
al.addAll(2, al2);
System.out.println("ArrayList1 after adding ArrayList2 at 3rd Pos:\n"+al);
}
}
3.获取ArrayList子集(subList)
使用:
List subList(int fromIndex, int toIndex)
import java.util.ArrayList;
import java.util.List;
public class SublistExample {
public static void main(String a[]){
ArrayList<String> al = new ArrayList<String>();
//Addition of elements in ArrayList
al.add("Steve");
al.add("Justin");
al.add("Ajeet");
al.add("John");
al.add("Arnold");
al.add("Chaitanya");
System.out.println("Original ArrayList Content: "+al);
//Sublist to ArrayList
ArrayList<String> al2 = new ArrayList<String>(al.subList(1, 4));
System.out.println("SubList stored in ArrayList: "+al2);
//Sublist to List
List<String> list = al.subList(1, 4);
System.out.println("SubList stored in List: "+list);
}
}
Original ArrayList Content: [Steve, Justin, Ajeet, John, Arnold, Chaitanya]
SubList stored in ArrayList: [Justin, Ajeet, John]
SubList stored in List: [Justin, Ajeet, John]
4.同样是清空操作,clear性能好于removeAll
5.比较2个ArrayList
import java.util.ArrayList;
public class Details
{
public static void main(String [] args)
{
ArrayList<String> al1= new ArrayList<String>();
al1.add("hi");
al1.add("How are you");
al1.add("Good Morning");
al1.add("bye");
al1.add("Good night");
ArrayList<String> al2= new ArrayList<String>();
al2.add("Howdy");
al2.add("Good Evening");
al2.add("bye");
al2.add("Good night");
//Storing the comparison output in ArrayList<String>
ArrayList<String> al3= new ArrayList<String>();
for (String temp : al1)
al3.add(al2.contains(temp) ? "Yes" : "No");
System.out.println(al3);
//Storing the comparison output in ArrayList<Integer>
ArrayList<Integer> al4= new ArrayList<Integer>();
for (String temp2 : al1)
al4.add(al2.contains(temp2) ? 1 : 0);
System.out.println(al4);
}
}
[No, No, No, Yes, Yes]
[0, 0, 0, 1, 1]
6.克隆一个ArrayList
import java.util.ArrayList;
public class Details {
public static void main(String a[]){
ArrayList<String> al = new ArrayList<String>();
//Adding elements to the ArrayList
al.add("Apple");
al.add("Orange");
al.add("Mango");
al.add("Grapes");
System.out.println("ArrayList: "+al);
ArrayList<String> al2 = (ArrayList<String>)al.clone();
System.out.println("Shallow copy of ArrayList: "+ al2);
//add and remove on original ArrayList
al.add("Fig");
al.remove("Orange");
//Display of both ArrayLists after add & remove
System.out.println("Original ArrayList:"+al);
System.out.println("Cloned ArrayList:"+al2);
}
}
7.将ArrayList转换为数组
方法1:手工方式
import java.util.*;
public class ArrayListTOArray {
public static void main(String[] args) {
/*ArrayList declaration and initialization*/
ArrayList<String> arrlist= new ArrayList<String>();
arrlist.add("String1");
arrlist.add("String2");
arrlist.add("String3");
arrlist.add("String4");
/*ArrayList to Array Conversion */
String array[] = new String[arrlist.size()];
for(int j =0;j<arrlist.size();j++){
array[j] = arrlist.get(j);
}
/*Displaying Array elements*/
for(String k: array)
{
System.out.println(k);
}
}
}
方法2:使用toArray方法
import java.util.*;
public class Example {
public static void main(String[] args) {
/*ArrayList declaration and initialization*/
ArrayList<String> friendsnames= new ArrayList<String>();
friendsnames.add("Ankur");
friendsnames.add("Ajeet");
friendsnames.add("Harsh");
friendsnames.add("John");
/*ArrayList to Array Conversion */
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
/*Displaying Array elements*/
for(String k: frnames)
{
System.out.println(k);
}
}
}
8.将数组转换为ArrayList
方法1:手工方式
import java.util.*;
public class Details {
public static void main(String[] args) {
/*ArrayList declaration*/
ArrayList<String> arraylist= new ArrayList<String>();
/*Initialized Array*/
String array[] = {"Text1","Text2","Text3","Text4"};
/*array.length returns the current number of
* elements present in array*/
for(int i =0;i<array.length;i++)
{
/* We are adding each array's element to the ArrayList*/
arraylist.add(array[i]);
}
/*ArrayList content*/
for(String str: arraylist)
{
System.out.println(str);
}
}
}
方法2:Arrays.asList()
import java.util.*;
public class ArrayToArrayList {
public static void main(String[] args) {
/* Array Declaration and initialization*/
String citynames[]={"Agra", "Mysore", "Chandigarh", "Bhopal"};
/*Array to ArrayList conversion*/
ArrayList<String> citylist= new ArrayList<String>(Arrays.asList(citynames));
/*Adding new elements to the converted List*/
citylist.add("New City2");
citylist.add("New City3");
/*Final ArrayList content display using for*/
for (String str: citylist)
{
System.out.println(str);
}
}
}
方法3:Collections.addAll
import java.util.*;
public class Example2 {
public static void main(String[] args) {
/* Array Declaration and initialization*/
String array[]={"Hi", "Hello", "Howdy", "Bye"};
/*ArrayList declaration*/
ArrayList<String> arraylist= new ArrayList<String>();
/*Conversion*/
Collections.addAll(arraylist, array);
/*Adding new elements to the converted List*/
arraylist.add("String1");
arraylist.add("String2");
/*Display array list*/
for (String str: arraylist)
{
System.out.println(str);
}
}
}
ArrayList和Vector对比
1.不同点
1) 线程同步: ArrayList 是非线程同步的,Vector 是线程同步的
2) 调整大小: 虽然两者大小都是动态分配的,但分配方式不同
ArrayList 每次增加一半大小
Vector 每次增加2倍
3) 性能: ArrayList 因为是非线程安全所以性能很好,
Vector 由于在操作中需要加锁以阻塞其他线程修改,所以性能比较差。
4) 快速失败:
首先,什么是快速失败?
如果一个集合(ArrayList, Vector等)在其创建了迭代器后又被修改,将抛出ConcurrentModificationException。
举个例子:
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Jack");
arrayList.add("Tom");
arrayList.add("Lucy");
arrayList.add("Brant");
/*Looping Array List using Iterator*/
System.out.println("Iterator");
Iterator iter = arrayList.iterator();
//remove one element
arrayList.remove(0);
while (iter.hasNext()) {
System.out.println(iter.next());
}
Iterator
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.dylan.collection.LoopArrayListExample.main(LoopArrayListExample.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
在你删除元素后,迭代器迭代的时候就抛异常了!
在这一点上,Vector创建的Enumeration迭代不是快速失败的。
2.相同点
1)内部都使用数组数据结构
2)两者返回的迭代器是快速失败的
3)两者都是按元素的插入顺序来排序的
4)都允许有重复值和null值
5)空间都是动态伸缩的
3.什么时候用ArrayList和Vector?
如果你需要线程同步,使用Vector,
其他绝大多数情况都是使用ArrayList。当然,ArrayList也可以使用下面方式实现线程同步:
//Use Collecions.synzhonizedList method
List list = Collections.synchronizedList(new ArrayList());
...
//If you wanna use iterator on the synchronized list, use it
//like this. It should be in synchronized block.
synchronized (list) {
Iterator iterator = list.iterator();
while (iterator.hasNext())
...
iterator.next();
...
}