ArrayList works on the principle of creating a array and adding elements to it.
ArrayList class has a member variable elementData which is a Object array;
Object[] elementData;
When we do List l = new ArrayList(); the array elementData is initalized with a size of 10
if you use List l = new ArrayList(5) then an array elementData is initalized with a size of 5
add(E element)
add(index i, E element)
On adding a element at a particular index in ArrayList, ArrayList checks if a element is already present at that index. If no than the element passed in add() is added at that index, otherwise a new array is created with the index kept vacant and the remaining element shifted to right.
For Eg:
List<Integer> l= new ArrayList<String>();
l.add(1);
l.add(2);
l.add(3);
for (int i: l)
system.out.println(l.get(i));
See also :
Difference between equals() and = =
Difference between Arrays.sort() and collections.sort()
Static varibale,static class,Static method
How to add instance of a class to list and then reterieve it
Difference between Array and ArrayList
Custom Exception in Java -Tutorial
ArrayList class has a member variable elementData which is a Object array;
Object[] elementData;
When we do List l = new ArrayList(); the array elementData is initalized with a size of 10
if you use List l = new ArrayList(5) then an array elementData is initalized with a size of 5
add(E element)
Inside .add() method there is this check. Before adding element into the array it will check what is the current size of filled elements and what is the maximum size of the array. If size of filled elements is greater than maximum size of the array(or will be after adding current element) then size of the array must be increased .
if it is completely filled that is all element 10 are filled a new array is created with a new capacity which is 1.5 of original array using Arrays.copyOf. If the elementData array is not exhausted the new element is added in the array.
So adding a element in a array may take more time as a completely new array needs to be created with greater capacity and the data in the old array is transferred into the new array.On adding a element at a particular index in ArrayList, ArrayList checks if a element is already present at that index. If no than the element passed in add() is added at that index, otherwise a new array is created with the index kept vacant and the remaining element shifted to right.
For Eg:
List<Integer> l= new ArrayList<String>();
l.add(1);
l.add(2);
l.add(3);
for (int i: l)
system.out.println(l.get(i));
See also :
Difference between equals() and = =
Difference between Arrays.sort() and collections.sort()
Static varibale,static class,Static method
How to add instance of a class to list and then reterieve it
Difference between Array and ArrayList
Custom Exception in Java -Tutorial
No comments:
Post a Comment