1

这是我正在使用的代码

    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)

4

1 回答 1

4

因为这条线:

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

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

如果要添加at 元素的副本,请编写:List0

sentanceParts.add(new ArrayList<String>(sentanceParts.get(0)));
于 2012-05-09T05:15:29.260 回答