swapWords 方法在 Java 中不返回修改后的 ArrayList<String>



我正在Java中开发一个swapWords方法,该方法将ArrayList作为参数,并将列表中的其他单词相互交换。但是函数只是返回默认的ArrayList

//return 'words' with swapped letters
public ArrayList<String> swapWords()
{
ArrayList<String> swappedWords = new ArrayList<String>(); //init an empty ArrayList<String>
swappedWords = words; //set swappedWords equal to the ArrayList that I want to swap the words
for(int i = 0; i < swappedWords.size()-1; i++)
{   
if(swappedWords.get(i+1) != null) 
{
swappedWords.set(i, swappedWords.get(i+1)); //set the value at index(i) equal to the value at index(i+1)
}
}
return swappedWords; //return the new modified swappedWords
}
public static List<String> swapWords(List<String> words) {
List<String> tmp = words;                    // if words can be modified
//        List<String> tmp = new ArrayList<>(words);   // if words can not be modified
for (int i = 0; i < words.size() - 1; i += 2)
Collections.swap(tmp, i, i + 1);
return tmp;
}

最新更新