0

I'm having problem with using ArrayList. First I'm new to Java, I'm trying to use ArrayList to store objects and now I want to print out all objects thats are items of the ArrayList. But somehow, the List printed out improperly, there are duplicated items (i'm sure there is only one item of them). Here are my code:

StringBuilder description = new StringBuilder();
    for (Unit u: diary.getUnitCollection()){
        for (AssessmentItem a: u.getAssessmentCollection()){
            for (Task t: a.getTaskCollection()){
                description.append(t.toString());
            }
            description.append(a.toString());
        }
        description.append(u.toString());
    }

and this is the result, as you can see, they are duplicated:

Java-Ass1
Java-Ass2
Java-Ass1
Java-Ass2

If I print the UnitCollection only, its display correctly but the format like this [item,..], I want to know what's wrong in the for loop.

1
  • 2
    I suggest you print a log to find out whats wrong. From the code you posted, nobody can tell where the result string is coming from (i'm assuming one of the toString(). Commented May 17, 2012 at 22:21

1 Answer 1

2

There can exist only two possibilities:

1) Your list contains same element - it is not set and it is possible
2) Some of your toString methods call another. For example u.toString() call a.toString() inside it or a.toString() call t.toString()

Sign up to request clarification or add additional context in comments.

1 Comment

You're rite on the money mate. I was ways over my head abt the for loop, but as your 2nd option reference, I went back to the class and see I did list its items in toString() using iterator. and now all works. Tks mate

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.