From the Java documentation an IndexOutOfBoundsException
is:
Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
(the hint is in the name).
Your list has only two elements and so the only indices 0
to 1
can be referenced without throwing this exception.
Check the list size before trying to retrieve an element at a given index. For list
ArrayList<String> myList = new ArrayList<>();
the maximal index that can be accessed without an exception being thrown is
myList.size()-1
because indices start at 0
and there is a unique index for every element. Use an if-statement to check whether the index you are trying to access is within bounds:
if (index < myList.size()) {
// Get value at in-bounds index
fruit = myList.get(index)
// Set value at in-bounds index
myList.set(index, "Orange")
}
In practice, it is rare to operate over specific indices in lists the way you've done in your code. As a data structure, lists work best when we want to iterate over a collection of elements and perform some operation over some or all of them (e.g. filtering and transformation).
// Filtering example
List<String> filteredList = new ArrayList<>();
for (String fruit: myList) {
if fruit.endsWith("berry") {
filteredList.add(fruit);
}
}
// Mapping example
List<String> mappedList = new ArrayList<>();
for (String fruit: myList) {
mappedList.add(fruit.toLowerCase());
}
If you wish to inspect and modify particular elements, a hash table may work better. This data structure is implemented as a HashMap
in Java. It associates every value with a unique key. The get(Object key)
method can be used for safe access to elements:
get(Object key) ... Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Below is a visual example of an 8-bucket hash table:
+------------------+
| Hash Table |
+------------------+
Index| Key | Value |
-----|--------|--------|
0 | null | null |
-----|--------|--------|
1 |"apple" | "red" |---> ["grapefruit","orange"] ---> ["avocado","green"]
-----|--------|--------|
2 | null | null |
-----|--------|--------|
3 |"banana"| "yellow"|
-----|--------|--------|
4 | null | null |
-----|--------|--------|
5 |"mango" |"orange"|---> ["strawberry", "red"]
-----|--------|--------|
6 | null | null |
-----|--------|--------|
7 |"grape" |"purple"|
-----|--------|--------|
Legend:
- Empty buckets shown as null
- Indices 1 and 5 shows collision of keys with chaining
- Each bucket stores fruit and its color
- ---> represents linked list for collision resolution