Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement negative indexes in java? [closed]

Tags:

java

arrays

In Python, you are allowed to use negative array indices to count starting from the right side of an array. For example, array[-1] is last element and array[-2] is the second last element in the array. How would you implement this in Java?

like image 894
aravinth Avatar asked May 02 '15 08:05

aravinth


People also ask

Can you use negative indexes in Java?

The negative index is also invalid in Java. If you try to access an array with an invalid index, Java will throw an ArrayIndexOutOfBoundException . If you try to store a double value in an int array, it will cause a compilation error. If memory is not used correctly, memory is wasted in the array data structure.

How do I resolve ArrayIndexOutOfBounds exception in Java?

To avoid the ArrayIndexOutOfBoundsException , the following should be kept in mind: The bounds of an array should be checked before accessing its elements. An array in Java starts at index 0 and ends at index length - 1 , so accessing elements that fall outside this range will throw an ArrayIndexOutOfBoundsException .

Is negative indexing possible in array?

Languages that implement multi arrays as true multi arrays — arrays of arrays — cannot have negative indexes.


1 Answers

Java does not support negative indexes, to access the last cell, you should use

array[array.length-1] = lastElement;
like image 103
Saurabh Jhunjhunwala Avatar answered Sep 23 '22 06:09

Saurabh Jhunjhunwala