'How to implement negative indexes in java? [closed]

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?



Solution 1:[1]

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

array[array.length-1] = lastElement;

Solution 2:[2]

Java subscript index starts with 0. No negative index can be used. If at all used then java will throw Array Index out of bounds Exception.

Solution 3:[3]

To implement something like this, you would have to create a circular, doubly linked list... I did not compile and test this, but this is the general idea...

public class LinkedList {
    Integer node;
    LinkedList next;
    LinkedList prev;
    public LinkList(Integer node) {
        this.node = node;
        this.next = this;
        this.prev = this;
    }
    public void insert(Integer node) {
        if(this.node == null) {
            this.node = node;
            this.next = this;
            this.prev = this;
        }
        else if(this.next == null) {
            this.next = new LinkedList(node);
            this.prev = node
            this.next.prev = this;
            this.next.next = this;
        }
        else {
            this.next(node, this);
        }
    }
    private void insert(Integer node, LinkedList head) {
        if(this.next == null) {
            this.next = new LinkedList(node);
            this.next.prev = this;
            this.next.next = head;
        }
        else {
            this.next(node, head);
        }
    }
    public Interger get(int index) {
        int cursor = 0;
        if(index == cursor) {
            return this.node;
        }
        else if(index < cursor) {
            return this.prev.get(index, cursor-1);
        }
        else {
            return this.next.get(index, cursor+1);
        }
    }
    private Interger get(int index, int cursor) {
        if(index == cursor) {
            return this.node;
        }
        else if(index < cursor) {
            return this.prev.get(index, cursor-1);
        }
        else {
            return this.next.get(index, cursor+1);
        }
    }
}
public static void main(String[] args) {
    LinkedList list = new LinkedList(new Integer(1));
    list.insert(new Integer(2));
    list.insert(new Integer(3));
    System.out.println(list.get(-1).toString());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Lawrey
Solution 2 Mohan Raj
Solution 3 mjgoonan