2016-10-11 4 views
-4

여러 필드가 포함 된 개체 배열이 있습니다. 생성자, 설정자 및 getter가있는 클래스가 있습니다. 필드 중 하나가 이름입니다. 배열의 모든 이름을 사전 순으로 정렬하여 나열하고 싶습니다. 누구든지 도움이 될 수 있습니까? 이것은 자바에 있습니다.특정 필드로 알파벳 배열을 정렬하는 방법

감사합니다.

+0

아마도. 어떤 언어로? 어떤 종류의 물건에 대해 이야기하고 있습니까? –

+0

먼저 떨어져 : 어떤 언어로 코딩하고 있습니까? 두 번째 : 귀하의 시도와 함께 몇 가지 코드를 게시하십시오. 우리가 당신을 도울 수있는 이런 식으로. [질문하는 방법] – Roy123

+1

얼마나 많은 언어와 얼마나 많은 종류의 배열/객체가 당신의 대답을 원하십니까? ...? – deceze

답변

0

Comparable 인터페이스를 사용하면됩니다.

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()); 
     } 
    } 
} 

출력을위한 콘솔을 참조하십시오 : 우리는 (이 예에서는 이름) 특정 브랜드의 될 수있는 클래스 자동차,

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()); 
    } 
} 

그리고 주요 있다고 가정하자.

+0

내 물건이 배열에 저장된다는 것을 이해하지 못한다 : movies [] movieArr = 새로운 영화 [0]; – Alex