2011-04-21 26 views
0

我试图理清一个ArrayList,但我不能换我的头周围比较。我不明白如何定义从文本文件创建的我的数组列表中的可排序字段。此外,我不确定比较器逻辑。在我看来,像创建一组比较函数,然后调用它们。这是真的?我想不通比较

到目前为止,我的代码如下所示:

public class coord implements Comparator<Sort> { 
    private int index; 
    private int index2; 
    private double dista; 
} 

public class Sort { 
List<Sort> coords = new ArrayList<Sort>(); 


public static void main(String[] args) throws Exception { 
    ArrayList dist = new ArrayList(); 
    File file = new File("2.txt"); 
    FileWriter writer = new FileWriter("2c.txt"); 
    try { 
     Scanner scanner = new Scanner(file).useDelimiter("\\s+"); 

     while (scanner.hasNextLine()) 
     { 
      int index = scanner.nextInt(); 
      int index2 = scanner.nextInt(); 
      double dista = scanner.nextDouble(); 
      System.out.println(index + " " + index2 + " " + dista); 
     } 
    } 
} 
     public class EmpSort { 
      static final Comparator<coord> SENIORITY_ORDER = 
             new Comparator<coord>() { 
       public int compare(coord e1, coord e2) { 
        return e2.index().compareTo(e1.index()); 
       } 
      }; 
      static final Collection<coord> coords = ; 

      public static void main(String[] args) { 
       List<Sorted>e = new ArrayList<Sorted>(coords); 
       Collections.sort(e, SENIORITY_ORDER); 
       System.out.println(e); 

我感谢所有帮助任何人都可以给。

+1

此代码是不完整的。尝试没有catch或finally子句。 – Srikanth 2011-04-21 20:27:48

+0

我认为你有一堆模板。使用铅笔和纸张绘制您的对象系统,显示层次结构和关系。这将需要10分钟的时间,并清除你的想法。 – slezica 2011-04-21 20:29:05

回答

1

比较逻辑是简单的。当对一组元素进行排序时,您有两个选择 - 使用每个元素上的Comparable(假设有一个)进行排序,或者提供一个比较器。如果你的数组包含复杂的元素或有不同的排序标准,那么后一种选择可能是你需要使用的。

每次所述比较器被称为必须说,如果元件1是“小于”元件2在这种情况下返回一个负数,元件1是元件3“大于”在这种情况下返回一个正数。否则,如果元素相等,则返回0.您也可以在比较值之前进行引用和空比较,以便null元素在逻辑上“小于”非空元素等等。

如果元素是“平等”,那么你可能希望通过二次字段进行排序,然后第三场和继续下去,直到排序顺序是明确的。

一类复杂的它有一个简单的比较字段一个& B和我们要排序上:

class Complex { 
    public String a = ""; 
    public String b = ""; 
} 

//... 

Collections.sort(someList, new Comparator<Complex>() { 
    public int compare(Complex e1, Complex e2) { 
    if (e1 == e2) { 
     // Refs could be null or equal 
     return 0; 
    } 
    if (e1 == null && e2 != null) { 
     return -1; 
    } 
    if (e2 == null && e1 != null) { 
     return 1; 
    } 
    if (e1.a == e2.a) { 
     return 0; 
    } 
    if (e1.a == null && e2.a != null) { 
     return -1; 
    } 
    if (e1.a != null && e2.a == null) { 
     return 1; 
    } 
    // Just use the Comparable on the fields 
    return e1.a.compareTo(e2.a); 
    } 
});