I have two classes, DataClass and MY GUI Class.
This is in my GUI Class
final ArrayList<DataClass> MarksData = new ArrayList<DataClass>();
I store 4 elements at a time [Mark1,Mark2,Mark3,Mark4]
How can I find all the maximum mark for Mark1
I tried Object obj = Collections.min()
but doesn't work since it's an arrayList
of type DataClass
.
Any help is appreciated :)
2 Answers 2
The best way to do this would probably be to use Collections.max()
, but to do this you need to implement Comparable<DataClass>
on the DataClass
class.
This interface lets you define a compareTo(DataClass o)
method where you can write the logic in that method to determine if it's less or greater than the other mark, and then Collections.max()
will take care of finding the maximum for you.
As noted in the comment, you can also write a custom comparator and use the variant of Collections.max()
which takes that custom comparator - but the logic you write to compare the marks is the same.
Note that if you want to find the minimum mark instead, go for Collections.min()
. All other details remain the same.
-
Or you can also write a Comparator. and use max(Collection coll, Comparator comp)Subir Kumar Sao– Subir Kumar Sao2012年11月19日 11:51:49 +00:00Commented Nov 19, 2012 at 11:51
-
The question says "maximum mark" but it appears the OP wants the minimum which could be the "best mark"Peter Lawrey– Peter Lawrey2012年11月19日 11:52:29 +00:00Commented Nov 19, 2012 at 11:52
-
@PeterLawrey Good point, missed that. Added a note about
min()
at the end.Michael Berry– Michael Berry2012年11月19日 11:54:14 +00:00Commented Nov 19, 2012 at 11:54
To use Collections.min() you must either make DataClass implements Comparable<DataClass>
or you must provide a custom Comparator<DataClass>
Mark1
,Mark2
, and so on...? Show us the source code ofDataClass
.