1

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)

2
  • 2
    The debugger is a wonderful thing. By learning how to use it you will have one more tool in your arsenal. Commented May 9, 2012 at 5:16
  • Yes I am aware of the debugger but it is too complicated to figure out why a reference was being made in two places as apposed to a copy of the data in memory when I have only been programming in this language for 10 something minutes. Commented May 9, 2012 at 7:05

1 Answer 1

4

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)));
Sign up to request clarification or add additional context in comments.

1 Comment

You already got the answer for duplication above: The constructor "new ArrayList(otherList)" makes a copy for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.