how to start array index from 1 in java

ht‮//:spt‬www.lautturi.com
how to start array index from 1 in java

In Java, the index of an array starts at 0 by default, meaning that the first element of the array is located at index 0, the second element is located at index 1, and so on.

If you want to start the index of an array from 1, you can use a wrapper class such as ArrayList or LinkedList that allows you to access the elements of the list using indices starting at 1.

Here's an example of how you can use an ArrayList to start the index of an array from 1:

List<String> list = new ArrayList<>();

list.add("apple");
list.add("banana");
list.add("cherry");

System.out.println(list.get(1));  // Output: "banana"

This code creates an ArrayList and adds three elements to it. The get method of the List interface allows you to access the elements of the list using indices starting at 1, so the call to get(1) will return the second element of the list, which is "banana".

Note that using a wrapper class such as ArrayList or LinkedList will add some overhead to your code, as these classes use additional memory and processing power to manage the indices and element storage. If you need to optimize the performance of your code, you may want to consider using an array with a custom index mapping instead.

For example, you can create an array of size n+1 and use the formula index = i + 1 to map the indices starting at 1 to the actual indices of the array. This will allow you to access the elements of the array using indices starting at 1 while still using the performance benefits of an array.

Created Time:2017-11-01 20:43:01  Author:lautturi