Hi,
I have class of student object with the String student name and double GPA they are stored in array. My GUI have button for sort by name and sort by grade. I want to sort the name and the grade and I want to sort it using Comparator, but I don't know what is Comparator and when to use it. Also what is the diffrnet between Comparator and Comparable.
sk8ergirl 0 Newbie Poster
Recommended Answers
Jump to Post[you] first need to convert Array into an ArrayList<Student>
No, he doesn't. Arrays can be sorted using
Arrays.sort
, which works just likeCollections.sort
, but for arrays.
Jump to PostThe way that
compare
works is that it returns a negative number if the first argument is less than the second, a positive number if the first argument is greater than the second and 0 if they're equal. Soreturn -1
means "o1 is less than o2", return 0 means …
Jump to PostThe normal sort is an ascending sort, the lesser objects sort before the greater, so is o2 is greater than o1 it will sort after it. Just think of numbers - you expect them to sort 1,2,3,4,5... smaller/lesser first, greater/larger after
All 9 Replies
kumar.bhatia18 0 Newbie Poster
kumar.bhatia18 0 Newbie Poster
sepp2k 378 Practically a Master Poster
kumar.bhatia18 0 Newbie Poster
sk8ergirl 0 Newbie Poster
sk8ergirl 0 Newbie Poster
sepp2k 378 Practically a Master Poster
sk8ergirl 0 Newbie Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.