-1

I'm trying to add a String before a specific element in my LinkedList ArrayList. I'm trying to shift every element from the specific index to the right in order to insert the new element. Can elements not be shifted in an arrayList? I receive the following error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2

Here is my insertBefore method:

public static void insertBefore() { 
    System.out.println("Which song would you like to add: ");
    element = scanner.next();   
    for(int i=linkedList.size(); i>index; i--){
        linkedList.set(index+1, linkedList.get(index));
    }
    linkedList.add(index, element);
}

This is my 5th attempt after trying out much simpler methods. Thanks for your answers in advance!

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Joe Smith
  • 57
  • 1
  • 9
  • 1
    Post [MCVE](http://stackoverflow.com/help/mcve), please. What is `linkedList` and `index`? (I guess `element` is `static String`) – MikeCAT Mar 05 '16 at 13:03
  • Sorry, I can't catch. – MikeCAT Mar 05 '16 at 13:07
  • Sorry for the misunderstanding, I have methods to go to the Next element, previous element ect.. This is why I use index to increment and decrement to find my current position. – Joe Smith Mar 05 '16 at 13:09
  • Possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – Raedwald Mar 05 '16 at 13:10
  • element is a normal 'String' to be entered by the user. – Joe Smith Mar 05 '16 at 13:10

2 Answers2

0

You can add elements with add(int index, E element) method at the specified position using ArrayList object. It shifts automatically the element currently at that position.

You are getting that exception because you are trying to replace an element at the second position when you just have two elements. See the documentation for more information.

nnunes10
  • 550
  • 4
  • 14
0

Why not

if(linkedList.size() > 0)
return  linkedList.get(linkedList.size() - 1);
Ricardo Gellman
  • 623
  • 7
  • 17