Sunday, 15 September 2013

Convert ArrayList to Array and reverse

Convert ArrayList to Array

import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<Integer> arrlist = new ArrayList<Integer>();

    // use add() method to add values in the list
    arrlist.add(10);
    arrlist.add(12);
    arrlist.add(31);
    arrlist.add(49);
	
    System.out.println("Printing elements of array1");

    // let us print all the elements available in list
    for (Integer number : arrlist) {
      System.out.println("Number = " + number);
    }  

    // toArray copies content into other array
    Integer list2[] = new Integer[arrlist.size()];
    list2 = arrlist.toArray(list2);

    System.out.println("Printing elements of array2");

    // let us print all the elements available in list
    for (Integer number : list2) {
      System.out.println("Number = " + number);
    }
  }
} 
Let us compile and run the above program, this will produce the following result:
Printing elements of array1
Number = 10
Number = 12
Number = 31
Number = 49
Printing elements of array2
Number = 10
Number = 12
Number = 31
Number = 49
We can use Objects inside the ArrayList:
ArrayList<SubCategories> arrSubCategories;
SubCategories[] subCategoriesData;
subCategoriesData = arrSubCategories.toArray(new SubCategories[arrSubCategories.size()]);
SubCategories Class is defined as below:
public class SubCategories {
 
    public String item;
    public String price;
 
    public SubCategories(){
         
    }
     
    public SubCategories(String item,String price){
        super();
        this.item = item;
        this.price = price;
    }
     
    public String getItem() {
        return item;
    }
 
    public void setItem(String item) {
        this.item = item;
    }
 
    public String getPrice() {
        return price;
    }
 
    public void setPrice(String price) {
        this.price = price;
    }

Convert Array to ArrayList

We just saw how to convert ArrayList in Java to Arrays. But how to do the reverse? Well, following is the small code snippet that converts an Array to ArrayList:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
 
...
 
String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = Arrays.asList(countries);
System.out.println("ArrayList of Countries:" + list);
The above code will work great. But list object is immutable. Thus you will not be able to add new values to it. In case you try to add new value to list, it will throw UnsupportedOperationException.

No comments:

Post a Comment