2014-11-25 40 views
0

在Java中複製字符串是否有很好的方法?我知道我可以做一些拼接黑客,但我想知道是否有更優雅的解決方案。在Java中複製字符串

我想複製ArrayList中的每個字符串一定的次數。但是,數組列表似乎不允許多次使用同一個對象。我正在尋找一種方法來複制字符串,以便我可以將它添加到ArrayList。

public class MyClass { 
    ArrayList<String> myArrayList; 

    /*more code*/ 

    public ArrayList<String> duplicate(int timesToCopy) { 

     ArrayList<String> newArrayList = new ArrayList<>(); 
     for(String s: myArrayList) { //cycles through all strings 
     for(int i = 1; i <= timesToCopy; i++) { //adds them timesToCopy amount of times 
      newArrayList.add(s); //doesn't work, only adds it once 
     } 
     } 
     return newArrayList; 
    } 
} 

如果我輸入值爲{「貓」,「狗」}我稱之爲複製一個ArrayList(3),我應該得到{「貓」,「貓」,「貓」,「狗」 ,「狗」,「狗」}

但是,我得到{「貓」,「狗」}。

我試着用

newArrayList.add(new String(s)); 

更換

newArrayList.add(s); 

,但它仍然無法正常工作。

也許我在我的代碼的另一部分有一個錯誤?

編輯:

好吧,我不知道發生了什麼,但它在某種程度上工作後,我什麼也沒做。

編輯2:

好的,問題再次出現。但是,我發現了這個問題!我打電話重複(3),因爲它是一個無效函數,認爲它會改變實例的ArrayList,而不是返回一個新的。我很愚蠢。

+0

您是否記得從'duplicate'分配結果,或者您只是重新遍歷'myArrayList',因爲它對我來說工作得很好。考慮提供一個[可運行的示例](https://stackoverflow.com/help/mcve),它可以證明你的問題。這會減少混淆和更好的反應 – MadProgrammer 2014-11-25 03:06:32

+1

無法重現:http://ideone.com/y0VH4w(也許你錯誤地查看了原始的'ArrayList')? – August 2014-11-25 03:08:05

回答

1

我不能確定你是如何調用你的方法,但我會在輸入List通過像這樣

public static List<String> duplicate(List<String> al, int n) { 
    List<String> ret = new ArrayList<>(); 
    for (String s : al) { 
     for (int i = 0; i < n; i++) { 
      ret.add(s); 
     } 
    } 
    return ret; 
} 

public static void main(String[] args) { 
    System.out.println(duplicate(Arrays.asList("dog", "cat"), 3)); 
} 

輸出是(的要求)

[dog, dog, dog, cat, cat, cat] 
0

您可以使用java.util.Collections.nCopies,其中,使得N個副本傳遞給它的對象:

public static ArrayList<String> duplicate(List<String> myArrayList, int timesToCopy) { 
    ArrayList<String> newArrayList = new ArrayList<>(); 
    for(String s: myArrayList) { //cycles through all strings 
     newArrayList.addAll(Collections.nCopies(timesToCopy, s)); 
    } 
    return newArrayList; 
}