How to Convert an Array to ArrayList In Java ?
Using Arrays.asList() method you can convert the given array to ArrayList in java. Let's see an example. The implementation of asList() method is like below in java.
The Program is
1. Performing adding of an element to the returned ArrayList, results an exception - java.lang.UnsupportedOperationException.
2. Performing removing of an element to the returned ArrayList also results an UnsupportedOperationException - java.lang.UnsupportedOperationException.
3. You can perform other operations such as - get(), contains(), indexOf() - as these are read only operations on the list and won't cause any structural change.
public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); }
The Program is
package com.speakingcs.collections; import java.util.Arrays; import java.util.List; public class ArrayToArrayList { /** * @param args */ public static void main(String[] args) { String[] strArr = {"abc","bcd","cde","def","efg","fgh","ghi","hij","ijk"}; convertToArrayList(strArr); } public static void convertToArrayList(String[] strArr) { List<String> aList = Arrays.asList(strArr); for(String str: aList) { System.out.println(str); } aList.add("jkl"); aList.add("klm"); } }Points To Note:
1. Performing adding of an element to the returned ArrayList, results an exception - java.lang.UnsupportedOperationException.
aList.get(0);
2. Performing removing of an element to the returned ArrayList also results an UnsupportedOperationException - java.lang.UnsupportedOperationException.
aList.remove("abc");
3. You can perform other operations such as - get(), contains(), indexOf() - as these are read only operations on the list and won't cause any structural change.
aList.indexOf("abc");
aList.contains("abc");
Comments
Post a Comment