Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Confusion on the Solution (Java)

Adrian Harischand

Jul 13, 2023

Greetings, can someone please explain why are we doing : result.add(new ArrayList<>(tempList)); instead of result.add(tempList); . I notice that there is a difference in output when we do this but why is that ?

0

0

Comments
Comments
Z
zaid 2 years ago

because its passed by reference so what will happen. you need to create a new instance of the list because if you don't, you will update the tempList thats inside the result list

In Java, when you pass an object (like an ArrayList) to a method or add it to another co...