首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java中实现负索引?

如何在java中实现负索引?
EN

Stack Overflow用户
提问于 2015-05-02 16:28:28
回答 3查看 33.5K关注 0票数 15

在Python中,允许使用负数组索引从数组的右侧开始计数。例如,array-1是数组中的最后一个元素,array-2是数组中的倒数第二个元素。在Java中如何做到这一点?

EN

回答 3

Stack Overflow用户

发布于 2015-05-02 16:30:30

Java不支持负索引,要访问最后一个单元格,您应该使用

代码语言:javascript
复制
array[array.length-1] = lastElement;
票数 31
EN

Stack Overflow用户

发布于 2015-05-02 17:33:34

要实现这样的东西,您必须创建一个循环的双向链表...我没有编译和测试这个,但这是一般的想法...

代码语言:javascript
复制
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());
}
票数 4
EN

Stack Overflow用户

发布于 2015-05-02 17:31:06

Java下标索引从0开始。不能使用负指数。如果使用了,那么java将抛出数组索引越界异常。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30000088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档