Java ArrayList
ArrayList:(Derived Data Type / Collections)
—> A normal Array have some limitations: 1.It can store same DataType elements/values, 2.It is Fixed Size.
—>To Overcome the above limitations we can use ArrayList Which can store multiple DataType elements/values & it as no-Limit of Size.
—>An ArrayList is a predefined Class, So we can call Methods using Object.
*Note: the name of the Object becomes the name of the ArrayList.
- ArrayList Declaration: Two ways we can declare ArrayList
- To store any type of elements. : ArrayList obj=new ArrayList();
Example: ArrayList list = new ArrayList();
2. To store same type of elements :
ArrayList <Datatype> obj=new ArrayList <Datatype> ();
Example: 1. ArrayList <String> list = new ArrayList <String>();//String type
2.ArrayList<Integer> list = new ArrayList <Integer>();//Number type
- Adding Values to ArrayList:
Example: 1.ArrayList <String> obj = new ArrayList <String>();
obj.add(“John”); //adding string element to ArrayList. Duplicate value also allowed.
2.obj.add(index no, ”String”); // Syntax to insert element in specific location.
obj.add(1, “Kakarla”); // Inserting element at index value :1
- To know Size of an ArrayList:
Example: System.out.println(obj.Size());
- Remove an Element from ArrayList:
Example: obj.remove(index no); // It removes the element stored in that index number.
- Reading Values from ArrayList: There are Two ways
Example: System.out.println(obj);// It print all the elements present in the ArrayList like: [value1,value2,value3]
2.To list values individually we use Loop statements like “for loop”(enhanced for loop / for each loop).
Example: for(datatype variable: Name of ArrayList) //here the DataType //Variable stores each value for every iteration of forLoop.
{
System.out.println(variable);// the variable contain the value
}
*Note: the for loop will get error when ArrayList contain Multiple DataType Values, So use “Object” as DataType for that variable in forLoop. In Java Object is a DataType which can support multiple DataType Values. We can use this for any variables like: Object a; just like string a; but the Object DataType “a”
can store multiple datatype values like: a=10; or a=raj; like this. Even a
normal Array can store multiple datatype value by using Object datatype like:
Example: int a[ ]=new int a[5]; //can store only integer values
Object a[ ]= new object[5]; // can store multiple datatype values
Example: for(Object variable: Name of ArrayList ) {
System.out.println(variable);
}
Comments
Post a Comment