`
iloveflower
  • 浏览: 80282 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

10 example of using ArrayList in Java >>> Java ArrayList Tutorial

 
阅读更多
ArrayList in Java is most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic resizable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both Iterator and ListIterator for iteration but it’s recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. But while using ListIterator you need to be little careful because ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous () and the element that would be returned by a call to next (). In this Java ArrayList tutorial we will see how to create Java ArrayList and perform various operations on Java ArrayList.
ArrayList has been modified in Java5 (Tiger) to support Generics which makes Java ArrayList even more powerful because of enhanced type-safety. Before Java5 since there was no generics no type checking at compile time which means there is chance of storing different type of element in an ArrayList which is meant for something and ultimately results in ClassCastException during runtime. with generics you can create Java ArrayList which accepts only type of object specified during creation time and results in compilation error if someone tries to insert any other object into ArrayList in Java; for example if you create an ArrayList of String object you can not store Integer on it because add() method of ArrayList will check Type before adding object into ArrayList in Java opposite to add() method of Java4 which accepts any object.


Java Arraylist with Generics in JDK 1.5

It’s also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. It’s recommended to synchronize the list at the creation time to avoid any accidental unsynchronized access to the list. Another better option is to use CopyOnWriteArrayList which is added from Java 5 and optimized for multiple concurrent read. In CopyOnWriteArrayList all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array and that's why it is called as "CopyOnWrite"


Example of ArrayList in Java

Let's see some example of creating ArrayList in java and using them, I have tried to provide as much example as possible to illustrate different operations possible on Java ArrayList. Please let me know if you need any other Java ArrayList examples and I will add them here.




1) Creating an ArrayList

You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety.

In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.




ArrayList stringList = new ArrayList();




2) Putting an Item into ArrayList

Second line will result in compilation error because this Java ArrayList will only allow String elements.

stringList.add("Item");

stringList.add(new Integer(2)); //compilation error




3) Checking size of ArrayList

Size of an ArrayList in Java is total number of elements currently stored in ArrayList.

int size = stringList.size();







4) Checking Index of an Item in Java Arraylist

You can use indexOf() method of ArrayList in Java to find out index of a particular object.

int index = stringList.indexOf("Item");







5) Retrieving Item from arrayList in a loop

Many a times we need to traverse on Java ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator.

We will see use of Iterator in next section.




for (int i = 0; i

   String item = stringList.get(i);

}




From Java 5 onwards you can use foreach loop as well

for(String item: stringList){

System.out.println("retreived element: " + item);

}




6) Checking ArrayList for an Item

Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.




7) Checking if ArrayList is Empty

We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty. isEmpty() method returns true if this ArrayList contains no elements.




boolean result = stringList.isEmpty();




8) Removing an Item from ArrayList

There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself.

Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.




stringList.remove(0);  

stringList.remove(item);







9) Copying data from one ArrayList to another ArrayList in Java

Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java. Below code will add all elements of stringList to newly created copyOfStringList.




ArrayList copyOfStringList = new ArrayList();

copyOfStringList.addAll(stringList);







10) Replacing an element at a particular index

You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2".




stringList.set(0,"Item2");




11) Clearing all data from ArrayList

ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing it.




stingList.clear();







12) Converting from ArrayList to Array in Java

Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.




String[] itemArray = new String[stringList.size()];

String[] returnedArray = stringList.toArray(itemArray);




13) Creating Synchronized ArrayList

Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.




List list = Collections.synchronizedList(new ArrayList(...));




14) Creating ArrayList from Array in Java

ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a)  method for this purpose which returns a fixed-size list backed by the specified array.




ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three");







15) Traversing in ArrayList in Java

You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing.




Iterator itr = stringList.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}




ListIterator listItr = stringList.listIterator();

while(listItr.hasNext()){

System.out.println(itr.next());

}







16) Sorting elements of ArrayList in Java

You can use Collections.sort(List list) method to sort a Java ArrayList in natural order defined by Comparable interface and can use Collections.sort(List list, Comparator c) method to sort your Java ArrayList based upon provided Comparator.







Tips on ArrayList in Java

1) ArrayList is not a synchronized collection hence it is not suitable to be used between multiple threads concurrently. If you want to use ArrayList then you need to either use new CopyonWriteArrayList or use Collections.synchronizedList() to create a synchronized List.

2) CopyonWriteArrayList is recommended for concurrent multi-threading environment as it is optimized for multiple concurrent read and creates copy for write operation.

3) When ArrayList gets full it creates another array and uses System.arrayCopy() to copy all elements from one array to another array.

4) Iterator and ListIterator of java ArrayList are fail-fast it means if Arraylist is structurally modified at any time after the Iterator is created, in any way except through the iterator's own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, that's why it’s called fail-fast.

5) ConcurrentModificationException is not guaranteed and it only thrown at best effort.

6) If you are creating Synchronized List it’s recommended to create while creating instance of underlying ArrayList to prevent accidental unsynchronized access to the list.

7) An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation due to incremental filling of ArrayList.

8) The size, isEmpty, get, set, Iterator, and ListIterator operations run in constant time because ArrayList is based on Array but adding or removing an element is costly as compared to LinkedList.

9) ArrayList class is enhanced in Java5 to support Generics which added extra type-safety on ArrayList. It’s recommended to use generics version of ArrayList to ensure that your ArrayList contains only specified type of element and avoid any ClassCastException.

10) Since ArrayList implements List interface it maintains insertion order of element and allow duplicates.

11)If we set Arraylist reference null in Java all the elements inside Arraylist becomes eligible to garbage collection in java , provided there are no more reference exists for those objects.




Hope this Java ArrayList tutorial will be helpful for beginners in Java.



Read more: http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html#ixzz1uaUxrye5
分享到:
评论

相关推荐

    intent传递ArrayList<T>

    当我们需要在不同的组件之间传递一个ArrayList<T>对象时,由于Intent默认只支持基本类型和Parcelable接口实现类的数据传递,因此,我们需要特殊处理ArrayList<T>,特别是当T是自定义的对象时。本篇将详细介绍如何...

    JNI与C++数据类型传递示例(包括ArrayList对象、ArrayList嵌套返回)

    一个C++(Ubuntu16.04+QT5.9.1)通过JNI,调用JAVA类及方法的示例。通过JNI传递和返回多种类型的参数,boolean ,int,String,ArrayList<string>,ArrayList嵌套ArrayList<ArrayList<String>>等。

    Java Methods-java.util.ArrayList.ppt

    * `ArrayList<E>()`:创建一个默认容量为 10 的空 ArrayList。 * `ArrayList<E>(int capacity)`:创建一个指定容量的空 ArrayList。 其中,E 是类型参数,用于指定 ArrayList 中元素的类型。 二、ArrayList 类的...

    Java ArrayList教程

    Java ArrayList教程 Java ArrayList是Java集合框架中的一种动态数组,继承了AbstractList,并实现了List接口。ArrayList位于java.util包中,使用前需要引入它。ArrayList是一个可以动态修改的数组,与普通数组的...

    跟我学Java-day14-ArrayList集合.pdf

    day14-ArrayList集合 1.ArrayList 1.1ArrayList类概述【理解】 ...ArrayList<String> array = new ArrayList<String>(); //添加元素 array.add("hello"); array.add("world"); array.add("java");

    Java设计二次元动漫人物演出活动小游戏代码.docx

    private static ArrayList<String> characters = new ArrayList<String>(); private static ArrayList<String> actions = new ArrayList<String>(); private static Random random = new Random(); public ...

    java中ArrayList的用法

    ArrayList<Object> list = new ArrayList<>(10); ``` 3. **从集合创建`ArrayList`**:可以直接从另一个集合创建一个新的`ArrayList`。 ```java Collection<String> collection = ...; ArrayList<String> list ...

    java桑硅谷 day23 晨考.zip

    TreeMap, ArrayList<City>> map = new TreeMap<>(); ArrayList<City> bj = new ArrayList<>(); bj.add(new City(1,"北京市")); ArrayList<City> tj = new ArrayList<>(); tj.add(new City(4,"天津市")); ...

    Arraylist例子代码 java

    ArrayList<String> list = new ArrayList<>(10); // 指定初始容量为10 ArrayList<String> list2 = new ArrayList<>(); // 不指定初始容量 ``` 2. **添加元素** 使用`add()`方法可以将元素添加到ArrayList的末尾...

    ArrayList.txt

    ArrayList<String> list=new ArrayList<String>(); 2、ArrayList(int initialCapacity)  //这是第三个构造方法,构造了一个指定大小但内容为空的链表。 //initialCapacity参数就是初始容量大小。 //如果你...

    java泛型学习ppt

    * 使用泛型:ArrayList<Integer> al2=new ArrayList<Integer>(); al2.add(new Integer(10)); Integer i2=al2.get(0); // 这里不必做强制类型转换。 泛型基础: * 在定义泛型类或声明泛型类的变量时,使用尖括号来...

    jni操作arraylist对象

    jclass arrayListClass = env->FindClass("java/util/ArrayList"); if (arrayListClass == NULL) { // 处理找不到类的错误 } jmethodID addMethod = env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object...

    java集合类详解(set list ArrayList等java集合类详述)

    Java 集合类详解 Java 集合类是 Java 语言中的一种基本数据结构,用于存储和操作大量数据。集合类可以分为三大类:Collection、List 和 Set。 Collection 是集合框架中的根接口,提供了基本的集合操作,如 add、...

    Java编程常用方法

    例如:ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); String fruit = list.get(0); // fruit 的值为 "apple" 2. size():该方法返回 ArrayList 中实际包含的元素个数。 ...

    Java中ArrayList的使用方法简单介绍

    在Java编程语言中,ArrayList是集合框架中的一种重要数据结构,属于List接口的实现类。ArrayList主要用于存储一组有序的、可变大小的对象序列。它的特点是允许快速的随机访问,但插入和删除元素时效率相对较低,因为...

    java中数组列表ArrayList的使用.doc

    ### Java中数组列表ArrayList的使用详解 #### 一、ArrayList简介 `ArrayList`是Java集合框架中的一个重要组成部分,属于`List`接口的一种实现。它提供了一种动态调整大小的数组,能够有效地存储和操作一系列元素。`...

    ArrayList演示

    ArrayList是Java编程语言中一种常用的动态数组,它属于Java集合框架的一部分,位于`java.util`包下。ArrayList类实现了List接口,提供了可变大小的数组,允许我们在列表的任何位置进行添加、删除和修改元素的操作。...

    泛型需要注意的问题Java系列2021.pdf

    在Java中,像`ArrayList<String> arrayList1 = new ArrayList<Object>()`这样的引用传递是不允许的。这是因为,泛型出现的原因就是为了解决类型转换的问题,而这种引用传递违背了泛型设计的初衷。在这种情况下,如果...

    Java ArrayList遍历修改代码实例解析

    Java ArrayList 遍历修改代码实例解析 Java ArrayList 是 Java 语言中最常用的集合框架之一,用于存储和操作大量数据。然而,在遍历 ArrayList 时,如果需要删除某些元素,可能会遇到 ...

Global site tag (gtag.js) - Google Analytics