Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List[List[T]] vs. ArrayList[ArrayList[T]]

 
Ed Beaty
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! I wrote a method that would iterate through a List of Lists of Integers and sum them all together. I ended up with:

public static int sum(List<List<Integer>> listOfLists){

int result = 0;
for (List<Integer> sublist: listOfLists)
for (Integer i: sublist)
result += i;
return result;
}

The problem is, when I try passing an ArrayList<ArrayList<Integer>> to the method, the program fails to compile with the error:

"The method sum(List<List<Integer>> in the type Test is not applicable for the arguments (ArrayList<ArrayList<Integer>> "

Worse, when I try to cast ArrayList<ArrayList<Integer>> to List<List<Integer>>, I get a "Cannot cast from ... to ..." error.

I'm sure I'm missing something here. Does anyone have any suggestions? I had hoped to eventually make a method to iterate through ANY Iterable<Iterable<Integer>> and sum them all, but my attempts fail with the same errors I described above.

Thanks for any help!
-Ed Beaty
 
Ed Beaty
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D'oh! This seems to work nicely:

public static int sum(List< ? extends List<Integer>> listOfLists){

int result = 0;
for (List<Integer> sublist: listOfLists)
for (Integer i: sublist)
result += i;
return result;
}

Still trying to get the hang of generics...

Thanks,
Ed
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you're using Iterators, why limit it to Lists?
 
Ed Beaty
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or go one step further and have it work on any Iterable class:



In the process of trying to get this to work, I learned about the joy of erasure! I wanted to make an class that could iterate through all the elements in an Iterable of Iterable OR an Iterable of Iterator. This way, you could either combine multiple Lists into a single List or combine multiple Iterators into a List, and then iterate through all their elements (assuming the Lists and Iterators were all of the same type.) I tried using the constructots:

MergedIterator(Iterable<? extends Iterator<E>> manyIterators) or
MergedIterator(Iterable<? extends Iterable<E>> manyIterable)

but unfortunately, they both get erased to

MergedIterator(Iterable)

at compile-time, causing a duplicate method name error. Sigh.

-Ed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic