以下是我正在使用的代码
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)
答案 0 :(得分:4)
由于这一行:
sentanceParts.add(sentanceParts.get(0));
sentanceParts
两次引用相同的List<String>
。
如果您要在元素List
处添加0
的副本,请写下:
sentanceParts.add(new ArrayList<String>(sentanceParts.get(0)));