2013-09-27 33 views
1

嘿,夥計們和gals。排序多個ArrayList建議?

背景: 我正在做一個高分計劃,要求5個名字和5個分數的作業。輸入相應分數的名稱後,程序按照最高分數對兩個ArrayList進行排序。最後,它按排序順序顯示他們的分數。

問題: 我有一段時間試圖排序ArrayLists的魔鬼,你有任何排序ArrayLists的建議嗎?

代碼:

import java.util.*; 

public class Assignment6 
{ 
    public static void main(String args[]) 
    { 
     ArrayList<String> names = new ArrayList(); 
     ArrayList<Integer> scores = new ArrayList(); 

     initializeArrays(names, scores); 
     //sortArrays(names, scores); 
     displayArrays(names, scores); 
    } 

     public static void initializeArrays(ArrayList names, ArrayList scores) 
     { 
      Scanner in = new Scanner(System.in); 
      for(int i=0; i<5; i++) 
      { 
       System.out.println("Enter the name for score # " + (i+1) + ": "); 
       names.add(in.next()); 
       System.out.println("Enter the score for score # " + (i+1) + ": "); 
       scores.add(in.next()); 
      } 
     } 

     public static void sortArrays(ArrayList names, ArrayList scores) 
     { 
      for(int i=0; i<5; i++) 
      { 
       if(scores[i] < scores[i+1]) 
       { 
        Collections.swap(scores,a, b); 
        Collections.swap(names,a, b); 

       } 
      } 
     } 

     public static void displayArrays(ArrayList names, ArrayList scores) 
     { 
      System.out.println("Top Scorers: "); 
      System.out.println(names); 
      System.out.println(scores); 
     } 


} 
+0

你有什麼問題? –

+0

Collections.swap()是一個方便的工具,爲您的目的!但是'a'和'b'是什麼?它們沒有在任何地方定義,編譯器消息應該儘可能多地叫喊。 – clwhisk

回答

4

與字段創建一個對象:namescoreimplements Comparable
然後有ONLY一個ArrayList使用Collections.sort(list);

+0

爲什麼有人要做基本的家庭作業使用Comparable? – clwhisk

+1

@clwhisk因爲它更簡單,更好的方法。 – Alex

+0

自己排列清單更簡單。一旦你瞭解如何比較元素,放置代碼的位置並不重要,你可以完成對它的排序。 – clwhisk

0

好吧,你要打印類似的東西A-{Bob, Alex, ...},其中鮑勃是一個名字和一個餘地,你可以使用一個對象做它由Alex描述,但如果其家庭作品我認爲你的老師想看到一些comuter科學數據結構,那樣的話Associative_array會更好。你可以在你身邊實現它,或者使用java實現。 Java爲我們提供了Map [T,V]和實現,因爲你的情況是TreeMap,其中T - 是範圍,V - 是Name的列表,因爲很多人可以有相同的範圍。 所以,結果結構會像

Map<String, List<String>> sortedScopes = new TreeMap<>(); 

和使用:

List<String> names = sortedScopes.get(scope); 
if(names == null){ 
    names = new ArrayList<>(); 
sortedScopes.put(scope, names); 
} 

names.add(name) 

在這種解決方案,你將有隻有2種方法初始化和顯示, 的範圍將執行關於清理需求

1

您可以將分數和名稱包裝到一個對象中並將其存儲在一個列表中。現在

class Result implements Comparable<Result>{ 

    private String name; 

    private int score; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public int getScore() { 
     return score; 
    } 

    public void setScore(int score) { 
     this.score = score; 
    } 

    @Override 
    public int compareTo(Result other) { 
     return this.score - other.score; 
    } 

} 

可以使用Collections.sort(List<Result>)基於最高分給他們整理出來。

+1

你見過Alex的回答,爲什麼你增加了重複? –

+0

@SergiiZagriichuk至少它從中刪除了一層抽象層。 – clwhisk