2014-11-10 2 views
0

3 개 이상의 Person 객체로 구성된 배열이 있는데, 각각을 비교하여 가장 젊고 가장 키가 큰 사람을 찾는 방법을 알아 냈습니다. 내 구현에서3 개 이상의 개체를 비교하는 방법은 무엇입니까?

public class Person { 

    private int age; 
    private int height; 

    public int Person(int age, int height) { 
     this.age = age; 
     this.height = height; 
    } 

    public int getAge() { return age; } 
    public int getHeight() { return height; } 
} 

, 정말 같은 배열에있는 사람의 개체를 추가 :

Array<Person> persons = new Array<Person>(); 
persons.add(new Person(28, 150)); 
persons.add(new Person(38, 155)); 
persons.add(new Person(18, 160)); 

배열을 감안할 때

가 어떻게이 사람을 비교합니까 객체 반복에서?

for(int i=0; i<persons.size; i++) { 
    Person person = persons.get(i); 

    // compare age and height? 
} 
+0

배열을 정렬하는 방법을 찾으셨습니까? –

+3

은 'comparable'또는 'comparator'인터페이스를 구현하고 구현에 따라'sort() '를 호출하면 정렬 된 배열/목록에서 맨 처음 사람을 얻을 수 있습니다. – TheLostMind

+0

답변 없음, public int Person (int age, int height) 메서드 return 문이 없거나 생성자로 작성하십시오. – Anptk

답변

1

당신은 정렬 할 수 있지만, 나는 이것을 원할 것입니다.

Person youngest = null; 
Person tallest = null; 
int lowest_age = 0; 
int tallest_height = 0; 

for(int i=0; i<persons.size; i++) 
{ 
    Person person = persons.get(i); 
    int age = person.getAge(); 
    int height = person.getHeight(); 

    if ((age < lowest_age || (youngest == null)) 
    { 
     lowest_age = age; 
     youngest = person; 
    } 

    if ((height > tallest_height || (tallest == null)) 
    { 
     tallest_height = height; 
     tallest = person; 
    } 
} 
+0

@Tirath - 잘 잡습니다. 내 마음은 C++에 있었다. 결정된! – selbie

1

것은이 같은 Comparable 인터페이스, 뭔가를 사용해보십시오 :

import org.apache.commons.lang.builder.CompareToBuilder; 

public class Person implements Comparable<Person> { 

    private int age; 
    private int height; 

    public int Person(int age, int height) { 
     this.age = age; 
     this.height = height; 
    } 

    public int getAge() { return age; } 
    public int getHeight() { return height; } 

    public int compareTo(Person other) { 
     return new CompareToBuilder().append(age, other.age).append(height, other.height).toComparison(); 
    } 
} 

을 그리고, 여기 당신이 그것을 사용하는 방법 :

persons.sort(); 

참고 : 당신이 내림차순으로 정렬 할 경우, 바로 전환 내부 속성 및 기타 개체의 속성은 다음과 같습니다.

public int compareTo(Person other) { 
    return new CompareToBuilder().append(age, other.age).append(other.height, height).toComparison(); 
} 
+0

이것이 내가해야하는 방법이라고 생각합니다. 방금 apache.commons.lang을 설치하고 멋지게 작업했습니다. 고마워요! 모두 도와 주셔서 감사합니다. – pakito

+0

반갑습니다. 내 답변 옆에있는 눈금 아이콘을 클릭하여 가장 좋은 답변이라고 생각되면 내 대답을 선택하십시오. 좋은 하루 보내세요 :-) –

관련 문제