This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Steve Dyke wrote:
What java.util.Comparator implementation should I use? I keep getting ClassCastException by just using Arrays.sort(this.defectcodearray);
Right, the ClassCastException is because without passing a Comparator, the argument has to be an array of items which implement Comparable, which array-of-String does not.
You have to write a Comparator yourself. It's really easy here, because you just want it to compare the defectcodearray items (or  or , you haven't said which,) and String has a compareTo() method you can use. It could just be as simple as
So then you pass an instance of this as the second argument to sort(), and Bob's your uncle.
Joined: Nov 16, 2004
Sorry for asking so many questions.
Do I put this compare class inside my class that I ma building the array in. Also what goes in the <String> part of the class?
I am want the defectcodearray elements sorted
Ernest Friedman-Hill wrote:and a "LIMIT 8" clause to just grab the top 8 items.
Be careful with that - it's a MySQL only technique. MS SQL Server for instance uses a TOP X directly after the SELECT keyword:
I notice that Statement has a setMaxRows() method. I vaguely recall using this in the past to return just one record from a potentially large ResultSet.
Joined: Nov 16, 2004
Ernest Friedman-Hill wrote:
Steve Dyke wrote:Sorry for asking so many questions.
No problem about all the questions -- happy to help.
or you could even nest it inside the other class, if you wanted. Doesn't matter.
Sounds like maybe I'm getting a little ahead of you here; sorry. So you just need to do something like
I would really rather use your, embed in my existing class, suggestion. However, I feel like the code for the class will be different and I cannot figure out how to add the to my class in its current form. When I just copy the code in I get the following
Class must implement the inherited abstract method Comparator.compare(Object, Object)
Thanks again for all the help.
author and iconoclast
Sorry, Steve. Without the generics, you have to assume that the Object arguments are really whatever type you think they're supposed to be, and cast them. So the compareTo method actually has to do this: