本文介绍了Java列表:从标识符获取下一个或上一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要按标识符导航到列表.

1-我管理/创建列表.

1- I manage/create a list.

2-我创建了从列表中获取标识符元素的下一项的功能

2- I create function to get next item of a identifier element from my list

您能帮我解决此代码吗?

Can you help me to fix this code?

准备列表

List<String> myList = new ArrayList<String>();
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");


public String function getNext(String uid) {

    if (myList.indexOf(uid).hasNext()) {
        return myList.indexOf(uid).nextElement();
    }
    return "";
}

public String function getPrevious(String uid) {
    return myList.indexOf(uid).hasPrevious() ? myList.indexOf(uid).previousElement() : "";
}

推荐答案

您可以使用索引查找String,这样可以更快,更简单地实现具有所需功能的函数.

You could use an index to lookup your String which is faster and simpler however to implement the functions as you have them.

public String getNext(String uid) {
    int idx = myList.indexOf(uid);
    if (idx < 0 || idx+1 == myList.size()) return "";
    return myList.get(idx + 1);
}

public String getPrevious(String uid) {
    int idx = myList.indexOf(uid);
    if (idx <= 0) return "";
    return myList.get(idx - 1);
}

使用List.get(i)O(1),这使保持索引成为最快的选项. List.indexOf(String)O(n).使用NavigatbleSet可能会很有吸引力,因为它是O(log n),但是创建对象的成本非常高,以至于在您看到好处之前,集合必须相当大. (在这种情况下,您将使用第一个选项)

Using a List.get(i) is O(1) which makes keeping the index the fastest option. List.indexOf(String) is O(n). Using a NavigatbleSet might appear attractive as it is O(log n), however the cost of creating an object is so high that the collection has to be fairly large before you would see a benefit. (In which case you would use the first option)

这篇关于Java列表:从标识符获取下一个或上一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 20:45