Primitive Values and ArrayLists – Collections, Part I: ArrayList

Primitive Values and ArrayLists

Since primitive values cannot be stored in an ArrayList<E>, we can use the wrapper classes to box such values first. In the following code, we create a list of Integer in which the int values are autoboxed in Integer objects and then added to the list. We try to delete the element with value 1, but end up deleting the element at index 1 instead (i.e, the value 20).

Click here to view code image

List<Integer> intList = new ArrayList<>();
intList.add(10); intList.add(20); intList.add(1);
System.out.println(intList);                                  // [10, 20, 1]
System.out.println(“Element to be removed: ” + 1);            // 1
System.out.println(“Element removed: ” + intList.remove(1));  // 20
System.out.println(intList);                                  // [10, 1]

The method call

intList.remove(1)

has the signature

intList.remove(int)

This signature matches the overloaded method that removes the element at a specified index, so it is this method that is called at runtime. We say that this method is the most specific in this case. For the code to work as intended, the primitive value must be explicitly boxed.

Click here to view code image

System.out.println(intList);                                  // [10, 20, 1]
System.out.println(“Element to be removed: ” + 1);                        // 1
System.out.println(“Element removed: ” +
                   intList.remove(Integer.valueOf(1)));       // true
System.out.println(intList);                                  // [10, 20]

The method call

Click here to view code image

intList.remove(Integer.valueOf(1))

has the signature

intList.remove(Integer)

This call matches the overloaded remove(Object) method, since an Integer object can be passed to an Object parameter. This method is the most specific in this case, and is executed.

12.4 Querying an ArrayList<E>

A summary of useful methods that can be used to query a list is provided below.

Click here to view code image

int size()                                           
From
 List<E>
interface
.

Returns the number of elements currently in the list. In a non-empty list, the first element is at index 0 and the last element is at size()-1.

Click here to view code image

boolean isEmpty()                                   
From
 List<E>
interface
.

Determines whether the list is empty (i.e., whether its size is 0).

Click here to view code image

E get(int index)                                    
From
 List<E>
interface
.

Returns the element at the specified positional index. The method throws an IndexOutOfBoundsException if the index is out of range (index < 0 || index >= size()).

Click here to view code image

boolean contains(Object element)                    
From
 List<E>
interface
.

Determines whether the argument object is contained in the collection, using object value equality. This is called the membership test.

Click here to view code image

int indexOf(Object o)                                
From
 List<E>
interface
.
int lastIndexOf(Object o)                            
From
 List<E>
interface
.

Return the indices of the first and last occurrences of the element that are equal (using object value equality) to the specified argument, respectively, if such an element exists in the list; otherwise, the value –1 is returned. These methods provide element search in the list.

Click here to view code image

List<E> subList(int fromIndex, int toIndex)         
From
 List<E>
interface
.

Returns a view of the list, which consists of the sublist of the elements from the index fromIndex to the index toIndex-1 (i.e., a half-open interval). A view allows the range it represents in the underlying list to be manipulated. Any changes in the view are reflected in the underlying list, and vice versa. Views can be used to perform operations on specific ranges of a list.

Click here to view code image

boolean equals(Object o)                            
From
 List<E>
interface
.

Compares the specified object with this list for object value equality. It returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal according to object value equality.

The method size() returns the number of elements in the list, and the method empty() determines whether the list is empty.

Click here to view code image

// [Naan, kayak, Bob, Rotator, Bob]
System.out.println(“The size of the list is ” + strList.size());          // 5
boolean result = strList.isEmpty();
System.out.println(“The list ” + (result ? “is” : “is not”) + ” empty.”); // false

The method get(int) retrieves the element at the specified index.

Click here to view code image

// [Naan, kayak, Bob, Rotator, Bob]
System.out.println(“First element: ” + strList.get(0);                 // Naan
System.out.println(“Last element: ” + strList.get(strList.size()-1));  // Bob

The equals() method of the ArrayList class can be used to compare two lists for equality with regard to size and corresponding elements being equal in each list.

Click here to view code image

List<String> strList2 = new ArrayList<>(strList);
boolean trueOrFalse = strList.equals(strList2);                        // true

The method subList() returns a view of a list—that is, a sublist of the list. As the view is backed by the underlying list, operations on the sublist will be reflected in the underlying list, as demonstrated by the following code:

Click here to view code image

out.println(“Underlying list: ” + strList); // [Naan, kayak, Bob, Rotator, Bob]
List<String> strList3 = strList.subList(1, 4);
out.println(“Sublist before remove: ” + strList3);    // [kayak, Bob, Rotator]
out.println(“Remove: ” + strList3.get(0));  // “kayak”
strList3.remove(0);                         // Remove element at index 0
out.println(“Sublist after remove: ” + strList3);     // [Bob, Rotator]
out.println(“Underlying list: ” + strList); // [Naan, Bob, Rotator, Bob]

The membership test is carried out by the contains(Object) method. We can find the index of a specified element in the list by using the indexOf() and lastIndexOf() methods.

Click here to view code image

boolean found = strList.contains(“Naan”);     // true
int index = strList.indexOf(“Bob”);           // 2
index = strList.indexOf(“BOB”);               // -1 (Not found)
index = strList.lastIndexOf(“Bob”);           // 4 (Last occurrence)

Again, these methods require that the element type provide a meaningful equals() method for object value equality testing.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *