Reputation: 2045
Here is the code I am using
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() );
}
And it is outputting this
Type a sentance for analysis...
test case
e:1
ae:2
which should be
Type a sentance for analysis...
test case
test:1
case:2
Why is my code not doing this? I thought I was setting the sentanceParts(0) not sentanceParts(1)
Upvotes: 1
Views: 92
Reputation: 55223
Because of this line:
sentanceParts.add(sentanceParts.get(0));
sentanceParts
is referencing the same List<String>
twice.
If you want to add a copy of the List
at element 0
, then write:
sentanceParts.add(new ArrayList<String>(sentanceParts.get(0)));
Upvotes: 4