这是我正在使用的代码

    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


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

最佳答案

由于这一行:

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


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

如果要在元素List上添加0的副本,请输入:

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

07-24 20:29