returning element at a certain position in a linked list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yolkman
    New Member
    • Sep 2006
    • 14

    #1

    returning element at a certain position in a linked list

    I have a linked list that contains 28 integer values. The method getPostion has an int as a parameter. I know that it will probably be easier to use an iterator to loop through each element in the list but I don't know to set it up. Could you provide me with an example as to how I would do this?
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    Originally posted by yolkman
    I have a linked list that contains 28 integer values. The method getPostion has an int as a parameter. I know that it will probably be easier to use an iterator to loop through each element in the list but I don't know to set it up. Could you provide me with an example as to how I would do this?
    That depends on what you start out with initially.

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html

    That is the javadoc on Linked Lists, but if you start out with the value that is in the list, you could either iterate through it or use the indexOf() method to find it (though if you used indexOf() you would have to use get(), it might be faster to iterate as you are going to go through the values anyway) and if you start out knowing its place in the list, it would be easier to use the get() command (which returns the object of that index).

    Iterators are instantiated through

    Iterator it = listname.iterat or();

    and iterated though with

    while (it.hasNext())

    Comment

    Working...