I was looking through the Java documentation, and I came across the clear() method of ArrayLists.
What’s the use of this, as opposed to simply reassigning a new ArrayList object to the variable?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because there might be multiple references to the one list, it might be preferable and/or more practical to clear it than reassigning all the references.
If you empty your array a lot (within, say, a large loop) there’s no point creating lots of temporary objects. Sure the garbage collector will eventually clean them up but there’s no point being wasteful with resources if you don’t have to be.
And because clearing the list is less work than creating a new one.