BasicCoder
BasicCoder

Reputation: 1681

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() : "";
}

Upvotes: 13

Views: 59017

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533530

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);
}

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)

Upvotes: 19

RoToRa
RoToRa

Reputation: 38400

Lists don't have a nextElement() method. indexOf returns the integer index of the item. You could simply add (or subtract) one to get the next (or previous) item:

public String function getNext(String uid) {
   var index = myList.indexOf(uid);
   if (index > -1) {
     try {
       return myList.get(i+1);
     } catch ( IndexOutOfBoundsException e) {
       // Ignore
     }
   }
   return ""; // consider returning `null`. It's usually a better choice.
}

However looking up an object with indexOf on ArrayList is a very slow process, because it has to check every single entry. There are better ways to this, but that depends on what you are actually trying to achieve.

Upvotes: 1

fortran
fortran

Reputation: 76067

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.

Upvotes: 4

Related Questions