1

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 :)

asked Nov 19, 2012 at 11:48
6
  • 1
    how do you determine what is the maximum mark? Commented Nov 19, 2012 at 11:49
  • What are Mark1, Mark2, and so on...? Show us the source code of DataClass. Commented Nov 19, 2012 at 11:50
  • simply traverse the list , take a temp variable storing the first array value , compare the two adjacent , if higher value is found replace it to temp var , in the end the temp var returns the max value , this is simple sorting algo Commented Nov 19, 2012 at 11:57
  • @RohitJain Here is my dataClass pastebin.com/jfsuydQG Commented Nov 19, 2012 at 11:58
  • @JamesHunter.. That link is not accessible in my office. You should post your code here. Try to extract relevant part and post taht. Commented Nov 19, 2012 at 12:01

2 Answers 2

5

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.

answered Nov 19, 2012 at 11:50
3
  • Or you can also write a Comparator. and use max(Collection coll, Comparator comp) Commented 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" Commented Nov 19, 2012 at 11:52
  • @PeterLawrey Good point, missed that. Added a note about min() at the end. Commented Nov 19, 2012 at 11:54
2

To use Collections.min() you must either make DataClass implements Comparable<DataClass> or you must provide a custom Comparator<DataClass>

answered Nov 19, 2012 at 11:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.