2013-09-27 37 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