2013-04-05 58 views
-2

在Java对象的名单上有这个类:排序根据布尔

public class Turn { 

public boolean turnMoved; 
public int moveSelectionX; 
public int moveSelectionY; 
public int moveTargetX; 
public int moveTargetY; 

public boolean turnFired; 
public int shotSelectionX; 
public int shotSelectionY; 
public int shotTargetX; 
public int shotTargetY; 

//Set this to true when doing a turn if we fired before moving 
//Else if we do move/shot in the wrong order, we might select an empty cell 
boolean firedFirst = false; 
} 

别处在我的计划,我创建这些对象的列表。一旦列表完成后,我想排序顺序列表,让所有满足1对象将在列表的前面,等:

  1. turnMoved & & turnFired ==真
  2. turnFired ==真
  3. turnMoved ==真
  4. turnMoved & & turnFired ==假

竟被什么d最简单的方法是做什么?

+1

你有什么试过? Web上必须有成千上万个示例,演示如何对Java中的对象列表进行排序。 – 2013-04-05 15:37:43

+0

可能重复的[如何排序集合?](http://stackoverflow.com/questions/2477261/how-to-sort-a-collectiont) – 2013-04-05 15:37:59

+0

你看了一下Comparable接口吗? http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html – 2013-04-05 15:38:23

回答

3

让您的课程实施Comparable<Turn>,编写一个compareTo,以反映您的偏好,并使用Collections.sort对列表进行排序。

+0

我在使用compareTo和布尔值时出现了一些问题。 会是这样的在第一部分的正确路线?目前我没有代码交付,所以无法测试。 public int compareTo(Turn t1){if(this.turnMoved == t1.turnMoved) return 0; else if(this.turnMoved> t1.turnMoved) return 1; else return -1; } – user2249693 2013-04-05 16:07:03

+0

你不能使用'''引用'boolean's,所以不可以,它可能不会是这样的。 :) – sidoh 2013-04-05 16:25:21

+0

if(this.turnMoved == true && t1.turnMoved == false)return 1,then? – user2249693 2013-04-05 16:27:43