在Python中,允许使用负数组索引从数组的右侧开始计数。例如,array-1是数组中的最后一个元素,array-2是数组中的倒数第二个元素。在Java中如何做到这一点?
发布于 2015-05-02 16:30:30
Java不支持负索引,要访问最后一个单元格,您应该使用
array[array.length-1] = lastElement;发布于 2015-05-02 17:33:34
要实现这样的东西,您必须创建一个循环的双向链表...我没有编译和测试这个,但这是一般的想法...
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());
}发布于 2015-05-02 17:31:06
Java下标索引从0开始。不能使用负指数。如果使用了,那么java将抛出数组索引越界异常。
https://stackoverflow.com/questions/30000088
复制相似问题