From the course: Learning Java Collections
Unlock the full course today
Join today to access over 24,800 courses taught by industry experts.
Sorting collections - Java Tutorial
From the course: Learning Java Collections
Sorting collections
- [Instructor] Let's take a closer look at sorting collections by walking through a few examples that use a natural sort order. We'll start by giving our room class a natural order. The order will sort the rooms in alphabetical order first by their name, and then by their type. To specify a natural order, a type must implement the comparable interface. So let's go ahead and honor room class. We'll implement the interface. The interface accepts a generic type argument. In this case, I'm going to specify that as room, this will allow an instance of a room to be compared against another instance of a room. Now you'll notice the compiler immediately complaints, and that's because we haven't satisfied the comparable interface. So just hover over the room class and then click on add unimplemented methods. And then you'll notice that within your room class, you'll get a CompareTo method. Now here we'll need to provide the logic…