|
This class extends AbstractList and implements the List interface.This class can be said to be the improved version of the arrays as in arrays we have the limitation of the fixed size which has to be known and defined well in advance and the n nothing much can be done with respect to the increase and decrease in the size of the array , so we have got the extended class from collections framework whch gives us the flexibility of having the variable array structure which can be dynamically increased or reduced as per the programmers need. An ArrayList is a variable-length array of object references.
ArrayList has three constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)
Array list (): This constructor builds an empty array list.
ArrayList(Collection c): This constructor builds an array list that is initialized with the elements of the collection c.
ArrayList (int capacity) : This constructor builds an array list that has the specified initial capacity. The capacity grows automatically as elements are added to an array list.
import java.util.ArrayList;
import java.util.List;
public class CreateArrayList {
public static void main(String args[]) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
}
}
The above code will create an ArrayList object and store three String objects in the ArrayList object.
import java.util.ArrayList;
import java.util.List;
public class DisplayArrayList {
public static void main(String args[]) {
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
for(int i = 0; i < 3; i++) {
System.out.println(list.get(i));
}
}
}
Output of the above code
1
2
3
Below code is an example where the arraylist contains many Employee objects. Try this code a see how it works.
import java.util.ArrayList;
import java.util.List;
public class Employees {
public static void main(String args[]) {
List employeesList = new ArrayList();
employeesList.add(new Employee("Sam", 100000));
employeesList.add(new Employee("Rohan", 200000));
employeesList.add(new Employee("John", 300000));
employeesList.add(new Employee("Willey", 400000));
int size = employeesList.size();
for (int i = 0; i < size; i++) {
Employee employee = (Employee) employeesList.get(i);
System.out.println(employee.toString());
}
}
}
class Employee {
private String name;
private long sal;
public Employee(String name, long sal) {
this.name = name;
this.sal = sal;
}
public String getName() {
return name;
}
public long getSal() {
return sal;
}
public String toString() {
return "Name : " + getName() + "\n" + "Salary of " + getName() + ": "
+ getSal();
}
}
|