Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list : get next or previous element from an identifier

I want to navigate into a list by identifier.

1- I manage/create a list.

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

Can you help me to fix this code?

Prepare the list

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() : "";
}
like image 867
BasicCoder Avatar asked Jun 20 '11 13:06

BasicCoder


1 Answers

If your elements are not repeated, what you need is a NavigableSet:

http://download.oracle.com/javase/6/docs/api/java/util/NavigableSet.html

The methods higher and lower are what you are looking for.

like image 181
fortran Avatar answered Sep 20 '22 06:09

fortran