-5 java
我创建了一个类 Car,具有这些属性和方法。我使用了一个列表来存储多个对象。
package com.company;
import java.util.ArrayList;
import java.util.Collections;
class Car implements Comparable<Car> {
private String manufacturer;
private int speed;
private double price;
private int year; // manufacture year
public Car(String manufacturer, int speed, double price, int year) {
this.manufacturer = manufacturer;
this.speed = speed;
this.price = price;
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public int getSpeed() {
return speed;
}
public double getPrice() {
return price;
}
public int getYear() {
return year;
}
public String toString() {
return this.manufacturer + ", speed: " + this.speed + "km/h, price: " + this.price + " USD, year: " + this.year;
}
public int compareTo(Car c) {
if (this.price == c.price)
return 0;
else if(this.price > c.price)
return 1;
else
return -1;
}
}
public class Solution {
public static void main(String[] args) {
List<Car> cars = new ArrayList<Car>();
cars.add(new Car("Audi", 280, 35300, 2018));
cars.add(new Car("Mercedes-Benz", 155, 80000, 2009));
cars.add(new Car("Toyota", 155, 18750, 2011));
cars.add(new Car ("Fiat", 140, 22500, 2000));
cars.add(new Car ("Land Rover", 209, 90900, 2014));
for (Car iterator: cars) {
System.out.println(iterator);
}
Collections.sort(cars);
for (Car iterator: cars) {
System.out.println(iterator.getPrice());
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用 Comparable 接口后,我想访问排序列表的第一个元素,例如,因为我想获得最便宜的汽车。我怎么能那样做?
小智 5
因为ArrayList您可以通过这种方式访问第一个元素:
cars.get(0);
Run Code Online (Sandbox Code Playgroud)
对于LinkedList:
cars.getFirst();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |