I am a new programmer learning about interfaces, and I was wondering if someone could explain how exactly the Comparable interface works. For example, I have two classes, one which implements Comparable and the other which uses Collections.sort to sort a collection of items using the compareTo method overridden in my class which implements Comparable. First off, why does calling Collections.sort ultimately result in the compareTo method being called? And how does the compareTo method work with only one argument? More specifically, when comparing this.price to temp.price, what is "this" referring to (I know it refers to the current object, but where is the object coming from?), and how does this end up sorting all elements in the list?
Class 1: Defines characteristics of each Item
package Item; import java.util.*; public class Item implements Comparable { private String id; private String name; private double retail; private int quantity; private double price; Item(String idIn, String nameIn, String retailIn, String quanIn) { id = idIn; name = nameIn; retail = Double.parseDouble(retailIn); quantity = Integer.parseInt(quanIn); if(quantity>400) price = retail*.5D; else if(quantity>200) price = retail *.6D; else price = retail*.7D; price = Math.floor(price*100+.5)/100; } public int compareTo(Object obj) { Item temp = (Item)obj; if(this.price < temp.price) return 1; else if(this.price > temp.price) return -1; return 0; } public String getId() { return id; } public String getName() {return name; } public double getRetail() {return retail;} public int getQuantity() {return quantity;} public double getPrice() {return price;} }
Class 2: Catalogs each item in a LinkedList
package Item; import java.util.*; //includes class Collections with method sort which implements Comparable public class Storefront { private LinkedList catalog = new LinkedList(); public void addItem(String id, String name, String price, String quant) { Item it = new Item(id, name, price, quant); catalog.add(it); } public Item getItem(int i) {return (Item)catalog.get(i);} public int getSize() {return catalog.size();} public void sort() {Collections.sort(catalog);} }
I didn't include my main class which just adds a few items then calls the sort() method in Storefront