![]() But we're doing something neat, we're declaring an anonymous inner type for this Comparator. || o1.equalsIgnoreCase("o") || o1.equalsIgnoreCase("u") Īlright, so you see here that we are using a Comparator inside of the Collections.sort() method. Return o1.equalsIgnoreCase("a") || o1.equalsIgnoreCase("e") || o1.equalsIgnoreCase("i") * true if the letter is a vowel, false otherwise * o1 the String that may or may not be a vowel * This method determine if the String being passed in is a vowel or not. Return o1.toLowerCase().compareTo(o2.toLowerCase()) It has a special notation, so if you don't quite get it, no worries: Collections.sort(theArrayList, new int compare(String o1, String o2) It's kind of like creating a whole class that can be used within an existing method. I'm going to be making use of something called an Anonymous Inner Type. If you study the Collections.sort() methods, you'll see that there's one that takes two parameters, a List and a Comparator, so this is the method we're interested in using. So let's get on with the good code where we make use of our Comparator. The resulting ArrayList would look like this:Īs you can see, that's not what we're looking for we want all the vowels to appear first. So you see here that we're populating an ArrayList with our “test” sentence and then we invoke the Collections.sort() method. TheArrayList.add("R") theArrayList.add("A") theArrayList.add("M") theArrayList.add("S") TheArrayList.add("P") theArrayList.add("R") theArrayList.add("O") theArrayList.add("G") TheArrayList.add("J") theArrayList.add("A") theArrayList.add("V") theArrayList.add("A") theArrayList.add(" ") TheArrayList.add("L") theArrayList.add("O") theArrayList.add("V") theArrayList.add("E") theArrayList.add(" ") TheArrayList.add("I") theArrayList.add(" ") construct the ArrayList with our letters So let's have a look at the code and how this can be made possible, here's the example of how to do a regular old sort of an ArrayList: public class SortingExample Well, since we are trying to sort an ArrayList of Strings then we will need to use the Comparator. Don't read anything else until you have come up with a guess in your mind. Okay, so given the information above, and knowing that we want to sort an ArrayList do you know which one of the interfaces you would use?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |