如何在java中实现负索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30000088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement negative indexes in java?
提问by aravinth
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 do this in Java?
在 Python 中,您可以使用负数组索引从数组的右侧开始计数。例如,array[-1] 是最后一个元素,array[-2] 是数组中的倒数第二个元素。你会如何在 Java 中做到这一点?
回答by Saurabh Jhunjhunwala
Java does not support negative indexes, to access the last cell, you should use
Java 不支持负索引,要访问最后一个单元格,您应该使用
array[array.length-1] = lastElement;
回答by Mohan Raj
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.
Java 下标索引从 0 开始,不能使用负索引。如果完全使用,那么 java 将抛出 Array Index out of bounds 异常。
回答by mjgoonan
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());
}