1

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);
 }
 } 
 }
Kannan Thangadurai
1,1452 gold badges18 silver badges37 bronze badges
asked Nov 12, 2015 at 5:45
6
  • I think you can use Map for this ? Commented Nov 12, 2015 at 5:46
  • 1
    Count each node up to the required index as iterate over the list. Insert the new node at that position and relink the links Commented Nov 12, 2015 at 5:50
  • Do you mean java.util.LinkedList when you say "linked list"? Surely list.set(5, object) does this? Commented Nov 12, 2015 at 5:51
  • are you implementing your own linked list ? or just using LinkedList<>? Commented Nov 12, 2015 at 5:52
  • @AndyTurner the parameters are list.set(Object name) Commented Nov 12, 2015 at 5:53

1 Answer 1

2

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)

answered Nov 12, 2015 at 5:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.