ArrayList (List) Methods Flashcards
Declaring a ArrayList
ArrayList arraylist = new ArrayList();
Adding an Item at the List
arraylist.add(“Element”);
Adding an element at a particular position of ArrayList
arraylist.add(3,Element);
Adding all element of a list to the end of the ArrayList
arraylist.addall(list-name);
Adding a list to a particular position of ArrayList
arraylist.addall(2,list-name);
Adding a ArrayList to Another ArrayList
arraylist-first.append(arraylist-second);
Removing an Item from the List (Any Element)
arraylist.remove(“Element”);
Removing an Item from a particular position of an ArrayList
arraylist.remove(2);
Retrieving an Item from an ArrayList based on the Index
arraylist.get(5)
Retrieving a sublist from an ArrayList <i>Based on Index</i>
arraylist.sublist(2,5)
Retrieving Index of an Item
arraylist.indexOf(“Element”);
Retrieving Last Index of an Item
arraylist.lastIndexOf(“Element”);
Size of an ArrayList
arraylist.size();
Sorting an ArrayList
Collection.sort(arraylist);
Reverse Sorting an Array List
Method 1 : Collection.reverse(arraylist);
Method 2 : Collection.sort (arraylist,Collection.reverseOrder());
Iterating over an ArrayList (Method 1: For Loop)
Method 1 - FOR LOOP
for (int counter = 0; counter < arraylist.size(); counter++) {
System.out.println(arraylist.get(counter));
}
Iterating over an ArrayList (Method 2: While Loop)
Method 2 - WHILE LOOP int count = 0; while (arraylist.size() > count) { System.out.println(arraylist.get(count)); count++; }
Iterating over an ArrayList (Method 3: ITERATOR)
Method 3 - ITERATOR
Iterator iterator = arraylist.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Is this item there in the ArrayList?
arraylist.contains(“Element”);
Swapping elements in an arraylist
Collection.swap(arraylist,1,4);
Difference between Array and ArrayList?
Contains:
Arrays can contain primitive or Objects
ArrayList can contain only Objects.
Size:
Arrays are fixed size
ArrayList size is dynamic.
Feature
Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator Set implementations: HashSet, LinkedHashSet, TreeSet etc.
When will you use Array over ArrayList?
Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.
If the size of list is fixed and mostly used to store and traverse them. For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types. If you are working on fixed multi-dimensional situation, using [][] is far more easier than List>