Java ArrayList

In Java, ArrayList is a collection of objects. When you add an number or string value to the ArrayList collection, the value will be converted to an object type.

import java.util.*;//don't forget to import this package
class JavaArrayList{
   public static void main(String args[])
  {
     ArrayList AL=new ArrayList(); //create object from ArrayList class
     int i;
     Object x;
     for(i=0;i<10;i++)
        AL.add(i,i*i); //add value to the object collection using add(index,value) method
  
     for(i=0;i<AL.size();i++){ //using size() method to return the number of elements in the object collection
       x=AL.get(i); //using get(index) method to read an element of the list by its index
       System.out.print(x+"\t");
    }

   for(i=0;i<AL.size();i++)
      AL.remove(i); //using remove(index) remove an element of the list by its index

    
  }
}


If you want to store integer values in the ArrayList collection, then read them back for calculations. How can you do?
//this code does not work
int val;
val=Integer.parseInt(AL.get(i));
System.out.println(val*100);

The solution i found is to store the integer values as string. Then you can convert the string values to integer values
for later calculations:
import java.util.*;//don't forget to import this package
class JavaArrayList{
   public static void main(String args[])
    {
     ArrayList AL=new ArrayList(); //create object from ArrayList class
     int i;
     int x;
     for(i=0;i<10;i++)
        AL.add(i,""+i*i); //store integer values as string type
  
     for(i=0;i<AL.size();i++){ //
      x=Integer.parseInt((String)AL.get(i)); //converst the element to string then to integer type
      System.out.print(x*100+"\t"); //now x is integer value can be calculated
    }

   for(i=0;i<AL.size();i++)
     AL.remove(i); //using remove(index) remove an element of the list by its index

    
  }
}

Posted by: Dara | post date: 01-23-2013 | Subject: Java Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.