2016-03-05 127 views
-1

我试图在LinkedList ArrayList中的特定元素之前添加一个字符串。 我试图将每个元素从特定索引转移到右侧以插入新元素。元素不能在arrayList中移动?我收到以下错误:LinkedList插入之前方法

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

这里是我的insertBefore方法:

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); 
} 

这是我尝试了很多简单的方法后,5日的尝试。提前感谢您的回答!

+1

请寄[MCVE](http://stackoverflow.com/help/mcve)。什么是'linkedList'和'index'? (我猜'元素'是'静态字符串') – MikeCAT

+0

对不起,我无法捕捉。 – MikeCAT

+0

对不起,我有方法去下一个元素,以前的元素等..这就是为什么我使用索引来增加和减少找到我的当前位置。 –

回答

0

您可以使用ArrayList对象在指定位置添加带有add(int index, E element)方法的元素。它会自动移动当前位置的元素。

你正在得到这个异常,因为当你只有两个元素时,你试图在第二个位置替换一个元素。有关更多信息,请参阅documentation

+0

谢谢,清晰简洁的回答。 –