更改ArrayList中的String元素<list <string>&gt;正在更改ArrayList </list <string>中的两个列表

时间:2012-05-09 05:11:20

标签: java arraylist

以下是我正在使用的代码

    ArrayList<List<String>> sentanceParts = new ArrayList<List<String>>();

    int i;

    sentanceParts.add(Arrays.asList(sentance.split("\\s+")));
    sentanceParts.add(sentanceParts.get(0));
    System.out.printf( "%s\n", sentanceParts.get(1).get(0));

    for( i = 0; i < sentanceParts.get(0).size(); i++ ){
        sentanceParts.get(0).set(i, 
        sentanceParts.get(0).get(i).replaceAll( "[^aeiou]+", "" ));
        System.out.printf( "%s:%d\n",
                sentanceParts.get(1).get(i),
                sentanceParts.get(0).get(i).length() );
    }

正在输出此

Type a sentance for analysis...
test case
e:1
ae:2

应该是

Type a sentance for analysis...
test case
test:1
case:2

为什么我的代码没有这样做?我以为我设置了sentanceParts(0)而不是sentanceParts(1)

1 个答案:

答案 0 :(得分:4)

由于这一行:

sentanceParts.add(sentanceParts.get(0));

sentanceParts两次引用相同的List<String>

如果您要在元素List处添加0副本,请写下:

sentanceParts.add(new ArrayList<String>(sentanceParts.get(0)));