简体   繁体   中英

How do I set an element in a linked list by the index?

So I need to make this method to set an element a certain object by index. For example I would input index 5, and it would set whatever I chose for the object in index 5. I'm using a linked list for this. Here's the method so far..

public void setElement(int index, Object element) {
   ListIterator iterator = listIterator();   
}

I have no clue how to do this. I'm using nodes by the way. Also the ListIterator class is just the ListIterator interface. It has the methods of next, hasNext, add, remove and set. I just don't know how I would go about doing this. Could someone guide me in the right direction?

EDIT: I'm using my own implemented link list.

Here's what I just wrote which seems like I'm on the right track, but it's still not working.

 public void setElement(int index, Object element) {
       ListIterator iterator = listIterator();
       int count = 0;      
       while(iterator.hasNext()) {
           count++;
           if(count == index){
               iterator.set(element);
           }
       }       
   }

I'm using a linked list

so considering you are using LinkedList

If you want to insert new object in the specific index and move next all elements to the right use

add(int index, E element)

add(int index, E element)

If you replace the existing object at the specific position

set(int index, E element)

set(int index, E element)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM