Advertisement
vencinachev

Comparable Interface

Mar 12th, 2021
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1.  
  2. public class Car implements Comparable {
  3.    
  4.     private String model;
  5.     private double price;
  6.     private int maxSpeed;
  7.  
  8.     public Car(String model, double price, int maxSpeed) {
  9.         this.model = model;
  10.         this.price = price;
  11.         this.maxSpeed = maxSpeed;
  12.     }
  13.    
  14.     public String getModel() {
  15.         return model;
  16.     }
  17.     public void setModel(String model) {
  18.         this.model = model;
  19.     }
  20.     public double getPrice() {
  21.         return price;
  22.     }
  23.     public void setPrice(double price) {
  24.         this.price = price;
  25.     }
  26.     public int getMaxSpeed() {
  27.         return maxSpeed;
  28.     }
  29.     public void setMaxSpeed(int maxSpeed) {
  30.         this.maxSpeed = maxSpeed;
  31.     }
  32.  
  33.     @Override
  34.     public String toString() {
  35.         return "Car [model=" + model + ", price=" + price + ", maxSpeed=" + maxSpeed + "]";
  36.     }
  37.  
  38.     @Override
  39.     public int compareTo(Object obj) {
  40.         Car other = (Car)obj;
  41.         if (this.maxSpeed > other.maxSpeed) {
  42.             return -1;
  43.         } else if (this.maxSpeed < other.maxSpeed) {
  44.             return 1;
  45.         }
  46.         return 0;
  47.     }
  48.    
  49. }
  50.  
  51. import java.util.ArrayList;
  52. import java.util.Collections;
  53.  
  54. public class Program {
  55.     public static void main(String[] args) {
  56.         ArrayList<Car> cars = new ArrayList<Car>();
  57.        
  58.         cars.add(new Car("Mercedes-Benz", 50055.3, 230));
  59.         cars.add(new Car("Lada Niva", 5005.3, 330));
  60.         cars.add(new Car("Opel Astra", 15005.3, 200));
  61.        
  62.         Collections.sort(cars);
  63.        
  64.         for (Car c : cars) {
  65.             System.out.println(c);
  66.         }
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement