I have an array with multiple arraylists of different sizes.
I want to find the index of the largest arraylist in the array. I tried this:
Collections.max(disc);
disc being the name of the array of arraylists.
ArrayList I believe doesn’t implement the Comparable interface so I can’t do it like this. Is there a way to make a custom comparable for sizes of ArrayLists?
Advertisement
Answer
If you want to know the index of the largest sub-ArrayList then you’re basically looking for an information relative to where the largest ArrayList is stored. This research is not based solely on the intrinsic characteristics of your biggest ArrayList but also on where it is located.
Using Collections.max won’t help you, even if you redefine its natural ordering providing a new Comparator
, because you would only get the largest ArrayList not the index where it is stored. If you want to find the index you have to manually loop the outer ArrayList and whenever you find a new largest sub-ArrayList save its index.
Of course, all of what I said is based on the sole condition that you’re interested in retrieving the index and not the biggest sub-ArrayList itself. If you’re simply looking for the biggest sub-ArrayList then Collections.max with a Comparator implementation is what you need.