简体   繁体   English

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

[英]swapWords method not returning modified ArrayList<String> in Java

I am working on a swapWords method in Java that takes an ArrayList as an parameter and swaps every other word in the list for each other. 我正在研究Java中的swapWords方法,该方法将ArrayList作为参数并将列表中的每个其他单词彼此交换。 But the function just returns the default 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM