2015-01-17 44 views
0

你好,我必须从Java中的arraylist获得最大数量。 ia m得到错误T-不在绑定的实现java内。朗。还有什么其他的方法可以对arralist进行分类。这是我的代码示例。最大数组列表编号

private void CreateHighestScorePlayer(LinearLayout layoutForHighScore) { 
    HighScoreManager highScoreManager = HighScoreManager.getInstance(getApplicationContext()); 
    ArrayList<Score> scores = highScoreManager.getScore(); 
    Collections.sort(scores); 
    scores.get(scores.size() -1); 

} 
+0

您需要为Score类定义一个自定义比较器。 –

+0

我知道它有任何其他的排序方式 – user3826166

+0

不可以。“Score”类必须是“Comparable”,或者你必须提供一个“Comparator”。 Java不知道如何自己对类进行排序。它应该如何分类,在哪些领域?你必须通过实现“Comparable”或传递一个自定义的“比较器”来告诉它。那有什么问题? –

回答

1

如果你想获得最大元素,你应该使用Collections.max方法。它有一个将自定义比较器作为参数的版本。

事情是这样的:

Score result = Collections.max(scores, new Comparator<Score>() { 
    @Override 
    public int compare(Score score1, Score score2) { 
     // Compare them here 
    } 
}); 
+0

Collection.max同一问题 – user3826166

+0

@ user3826166您是否正在使用比较器的版本? – kraskevich

3

Collections.sort是具有以下特征的一般方法:

public static <T extends Comparable<? super T>> void sort(List<T> list) 

这意味着您必须作为参数传递一个List<T>,其中T延伸Comparable<? super T>

所以,你有两种解决方法,你可以把你Score类为

class Score implements Comparable<Score> { 

    public int compareTo(Score other) { 
    ... 
    } 
} 

或者你可以通过自定义Comparator为你的分数类中使用Collection.sort(List<T>, Comparator<? super T> c)

假设您可以控制Score类,第一种解决方案会更好,因为它会给出得分与其他得分自然排序的特征。

2

您需要让您的Score对象实施Comparable,然后在您的ArrayList上致电Collections.max。或者您可以使用Comparator来呼叫max的重载版本。无论哪种方式,你的代码都需要知道什么使得一个对象变大,变小或等于另一个。

我们实际上在ComparableComparator上创建了一个带有示例代码的视频教程,您可以找到here。关键是要了解两者在决定使用哪个方面的区别。

0

如果你只是想找到最高分数,你可以使用一个简单的Java 8构造。如果您Score类看起来像下面这样:

public static class Score { 
    private final int score; 

    Score(int score) { 
     this.score = score; 
    } 

    public int getScore() { 
     return score; 
    } 
} 

然后,您可以streamList<Score>这样的:

List<Score> scores = 
     Arrays.asList(new Score(100), new Score(200), new Score(50)); 

final Optional<Score> max = 
     scores.stream().max((score1, score2) -> Integer.compare(score1.getScore(), score2.getScore())); 

if (max.isPresent()) { 
    Score score = max.get(); 

    // Do stuff 
} else { 
    // Handle when there are no scores 

} 

这也采用了Comparator在一些其他的答案描述。 Comparator构建为这样的lamdba:

(score1, score2) -> Integer.compare(score1.getScore(), score2.getScore())