ArrayList
Unlike ordinary arrays, the ArrayList from the java.util package is an automatically expanding array. When you create an object of type ArrayList , you do not need to specify its dimension. For example,
ArrayList list = new ArrayList();
Advantages ArrayList compared to a regular array:
- fast access to elements by index in constant time
O(1) ;
- access elements by value in linear time
O(n) ;
- allows you to store any value, including
null .
Weaknesses ArrayList :
Inserting/removing an element causes overwriting of all elements placed "to the right" in the list one position to the left, that is, it works in linear time O(n) ;
Remember that lists can only contain objects, so if you want to store numbers use Integer instead of int . Integer is the name of a class, and an object of this class can contain an integer value. You can read more about classes and objects here: introduction to object-oriented programming.
|
There are two options for adding an element to an ArrayList:
add(value); - adding a value to the end of the ArrayList
add(index, value); - adding a value to the right place by index.
For example:
arr.add(10); span>
arr.add(5,10);
|
To get the value of an element from an ArrayList, use the get(index) method
For example:
To find out the number of elements in an array, you can use the size() method
For example:
|
To change the value by index in the list, use name.set(index,value);
|
There are two options for adding an element to an ArrayList:
add(value); - adding a value to the end of the ArrayList
add(index, value); - adding a value to the right place by index.
For example:
arr.add(10); span>
arr.add(5,10);
|
You can remove elements in an ArrayList using the remove method in two ways:
- by index remove(index)
- by value remove(value)
For example:
arr.remove(0); span> //removes the first element
arr.remove(< strong>new Integer(10)); //deletes element with value 10
|
Reverse ArrayList
The Collections interface also provides methods for bulk operations that work on the entire collection:
containsAll - returns the boolean value true if this collection contains all the elements in the called collection, otherwise it returns false .
addAll - adds all of the specified elements to the specified collection. The elements to be added can be specified individually or as an array.
removeAll - is used to remove all elements from the list that are contained in the specified collection.
clear - remove all elements
reverse - array reverse
etc.
Example
Using removeAll .
ArrayList<Integer> first = new ArrayList<Integer>();
first.add(1);
first.add(2);
first.add(3);
ArrayList<Integer> second = new ArrayList<Integer>();
second.add(1);
second.add(2);
// removes all elements from the second list,
// if they exist in the first list
second.removeAll(first);
|