1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java finding a specific element

  1. Aug 6, 2011 #1
    i am using dummy nodes for a doubly linked list and trying to get an object at the specified index. for whatever reason, when i test it, i am getting data but it is backwards. for example, when i have a list of integers from 0 to 21, and i attempt to call get(2), i get 19 which is at index 2 starting at the back of the list. since i am setting the cursor to be at the head, i am not sure what is causing this.


    public Object get(int index) {
    if (index < 0 || index > size()-1) throw new IndexOutOfBoundsException();
    Node cursor = _head._next;
    for (int i = 0; i < index; i++)
    cursor = cursor._next;
    return cursor._data;
    }
     
  2. jcsd
  3. Aug 6, 2011 #2

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    It's hard to tell without seeing your whole program, but I put good odds on the explanation that you are inserting things into the list in the wrong order. (e.g. you keep inserting new elements in the front of the list)


    Have you checked that the contents of the list really are what you expected? Have you put debugging statements into your code so that you can observe things throughout the entire execution of your program? (or otherwise used some means to trace your programs execution)

    Remember that you aren't supposed to be learning just how to program -- you're also supposed to be learning how to debug a programs.
     
  4. Aug 6, 2011 #3
    Is this method inside a class called something like "LinkedList"? And I'm guessing that this class has a variable for head and a variable for tail? If so, I see some problems.

    First, why have you added an underscore before the names of the instance variables? Second, you should not be accessing the variable "_next" like you are. You should have a getter in Node for this variable. At any rate, I suggest you do what Hurkyl suggested.
     
  5. Aug 6, 2011 #4
    i checked if the contents were correct, but when i try to add to my list, i am seeing garbage values rather than the integers that i intended to add to my list. as for debugging, i am unsure of how to do thisthoroughly. thanks for the suggestion.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java finding a specific element
Loading...