我正在研究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;
}

08-07 18:45