The task is to sort the objects. You must create a list of twenty objects. Each object is a room with a randomly given width and length.
The RoomComporator class implements the Comporator interface. I want to sort the rooms according to their area using the following command: Collection.sort (list, new RoomComparator ())
Sort the list to display on the console. The question is that I don’t understand how Collection.sort works when there is an object of another class in the argument. My code returns zeros.
Here is the code for the RoomComporator class:
import java.util.Comparator; public class RoomComporator implements Comparator<Room> { public RoomComporator(){} @Override public int compare(Room r1, Room r2 ) { return r1.square- r2.square;} } And the code for the main class Room:
import java.util.List; import java.util.Collections; import java.util.LinkedList; public class Room { int length; int width; int square; public int getWidth(){ return this.width; } public void setWidth(int width){ this.width = width; } public int getLength(){ return this.length; } public int setLength(int length){ return this.length = length; } public Room(int l, int w) { this.length = l; setWidth(w); } void square(){ int l, w; l = length; w = width; int s = w*l; System.out.println(s); } Room (int square){ this.square=square; } void printRoom(){ System.out.println(length + " " + width); } public static void main(String[] args){ List<Room> rooms = new LinkedList <Room>(); int numRooms = 20; int maxLength = 9; int maxWidth = 9; for( int i = 0; i < numRooms; i++) { int length = 1 + (int)(Math.random()*maxLength); int width = 1 + (int)(Math.random()*maxWidth); Room r = new Room(length, width); System.out.println("Room " + (i + 1)); r.printRoom(); r.square(); rooms.add(r); } for( int i = 0; i < numRooms; i++){ Collections.sort(rooms, new RoomComporator()); System.out.println(rooms.get(i).square);} } }