如何按特定字段按字母顺序对对象数组进行排序

时间:2016-10-11 07:01:36

标签: java arrays sorting alphabetical

我有一个包含许多字段的对象数组。我有一个带有构造函数,setter和getter的类。其中一个字段是名称。我想按字母顺序排序数组中的所有名称并列出它们。任何人都可以帮忙吗?这是在java。

由于

1 个答案:

答案 0 :(得分:0)

您可以使用Comparable接口执行此操作。让我们假设我们有一辆Class Car,它可以是某个品牌(在这个例子中是名字)

public class Car implements Comparable<Car> {


    private String name;
    private String color;   

    /**
     * Names
     */
    public enum Name {

        FIAT("fiat"), RENAULT("renault"), HONDA("honda");

        private final String name;      

        private Name(final String name) {
            this.name = name;
        }

        public String toString() {
            return this.name;
        }
    }

    /**
     * Colors
     */
    public enum Colors {

        BLUE("blue"), RED("red"), YELLOW("yellow");

        private final String color;     

        private Colors(final String color) {
            this.color = color;
        }

        public String toString() {
            return this.color;
        }
    }

    /**
     * Construct car with name and color
     * @param name
     * @param color
     */
    public Car(Name name, Colors color) {
        this.name = name.toString();
        this.color = color.toString();
    }

    /**
     * return name
     * @return
     */
    public String getName() {
        return this.name;
    }

    /**
     * compare to other car
     */
    @Override
    public int compareTo(Car car2) {
        return this.name.compareTo(car2.getName());
    }
}

主要:

import java.util.Arrays;

public class Main {

    //private static List<Car> cars = new ArrayList<Car>();
    private static Car[] cars = new Car[3];

    /**
     * @param args
     */
    public static void main(String[] args) {

        System.out.println("Create cars in array");
        cars[0] = new Car(Car.Name.RENAULT, Car.Colors.YELLOW);
        cars[1] = new Car(Car.Name.HONDA, Car.Colors.BLUE);
        cars[2] = new Car(Car.Name.FIAT, Car.Colors.RED);

//      System.out.println("Create cars in arraylist");     
//      cars.add(new Car(Car.Name.RENAULT, Car.Colors.YELLOW));
//      cars.add(new Car(Car.Name.HONDA, Car.Colors.BLUE));
//      cars.add(new Car(Car.Name.FIAT, Car.Colors.RED));

        System.out.println("Print cars");
        for (Car car : cars) {
            System.out.println("Car name: "+car.getName());
        }

        // sort cars, see Car class
        Arrays.sort(cars);

        System.out.println("Print cars after sort");
        for (Car car : cars) {
            System.out.println("Car name: "+car.getName());
        }
    }
}

请参阅控制台输出。