You have a couple of problems here, with both proposed solutions.
- Your
List<List> listofuserdetailsperAccount
object is not properly typed, as the inner List
is a raw type, something to be avoided. Assuming your inner list holds UserDetail
objects, your list of lists should be of type List<List<UserDetail>>
.
You don't use the for-each loop syntax to iterate over a List
, which is Iterable
.
for(List<UserDetail> innerList : listofuserdetailsperAccount)
- In Way 2 you initialize
List
to a new ArrayList
(which is a raw type, it should be new ArrayList<>()
if you needed this) and then promptly overwrite this value with the contents of your outer list. This means you ask Java to construct a new object that is then immediately cleaned up by the garbage collector, unused. This is wasteful and unnecessary.
In summary, you likely want to do:
List<List<UserDetail>> listofuserdetailsperAccount = // initialize your list
for(List<userDetail> innerList : listofuserdetailsperAccount) {
// do work with your innerList now
}
You commented (tidied up):
So while initializing I am doing something like this now, can you please let me know if this is correct:
List<List<String>> listofAccountdetailsLoggedinUser = null;
listofAccountdetailsLoggedinUser = new ArrayList<List<String>>();
OR I should not put it as null
and directly create an object like this:
List<List<String>> listofAccountdetailsLoggedinUser =
new ArrayList<List<String>>();
- That is the right track, but you do not need to initialize the variable to
null
. It doesn't hurt anything, since it doesn't construct an unnecessary object, but there's no reason to - you can declare and initialize the variable in one line, like you do in your second example.
Additionally, you don't need to specify the type of the ArrayList on the right hand side, simply use the diamond operator <>
, like so:
List<List<String>> listofAccountdetailsLoggedinUser = new ArrayList<>();
- Also, consider a shorter variable name, there's no need to use such a long one, and it's no fun to type :)