0

I'm working on some LeetCode practice with binary search trees. I'm wondering if someone might explain the following method signature:

 public List<List<Integer>> levelOrder(TreeNode root) {

I am confused by the use of Java Generics here -- what exactly List<List<Integer>> is saying in this case.

I understand Java Generics to be a way to "The <...> syntax allows you to write generic classes and methods that can handle multiple different types" according to https://programming.guide/java/less-than-greater-than-syntax.html

and I've seen it with with ArrayLists, but what does this specific definition of an integer list mean here?

Thanks

3
  • It's a list of integer lists Commented Feb 21, 2020 at 17:57
  • List<List<Integer>> can be parsed List<A> where A is List<Integer>. So what you have is a list containing lists of integers. Commented Feb 21, 2020 at 18:02
  • @littlebenlittle and Joelius Thanks! Commented Feb 21, 2020 at 18:05

1 Answer 1

1

List<List<Integer>> should be read as "a list of list of integers".

If you were defining "a list of list of integers" in pseudo-code it might look like this:

[ [ 1, 2, 3 ], [], [ 4, 5 ], [] ]

An ArrayList is a kind of List. Every ArrayList is a List, but not every List is an ArrayList.

The reason Java does this is because you (usually) do not want your code to depend on a specific implementation of a list, but rather the contract of a list instead.

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

Comments

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.