2

我有一个包含 CricketLiveScore 对象的 ArrayList

  CricketLiveScore{
     String homeAbbrevation;
   }

   List myList=new ArrayList<CricketLiveScore>();
   CricketLiveScore c1=new CricketLiveScore();
   c1.setHomeAbbrevation("IND vs PAK");
   CricketLiveScore c2=new CricketLiveScore();
   c2.setHomeAbbrevation("SRI vs NWZ");
   CricketLiveScore c3=new CricketLiveScore();
   c3.setHomeAbbrevation("AUS vs BAN");
   CricketLiveScore c4=new CricketLiveScore();
   c4.setHomeAbbrevation("NWZ vs IND");

   list.add(c1);
   list.add(c2);
   list.add(c3);
   list.add(c4);

我需要基于 Object 对这个 Arraylist 进行排序,其值 IND 在 home abbrevation 有人可以帮助解决这个问题,以便我需要一个列表进行排序并显示输出首先包含 IND 的值。

4

5 回答 5

2

尝试这个:

public class CricketLiveScoreComparator implements Comparator<CricketLiveScore> {
    @Override
    public int compare(CricketLiveScore c1, CricketLiveScore c2) {
        return c1.getHomeAbbrevation().compareTo(c2.getHomeAbbrevation());
    }
}

然后调用排序操作:

Collections.sort(myList, new CricketLiveScoreComparator());
于 2013-06-07T13:07:07.873 回答
1
  public class CricketSort implements Comparator<CricketLiveScore> {

    String countryOnTop;

    public CricketSort(String countryOnTop) {
        this.countryOnTop = countryOnTop;
    }

    @Override
    public int compare(CricketLiveScore o1, CricketLiveScore o2) {
        if (o1.homeAbbrevation.contains(countryOnTop)) {
            return -1;
        }
        if (o2.homeAbbrevation.contains(countryOnTop)){
            return 1;
        }
        return o1.homeAbbrevation.compareTo(o2.homeAbbrevation);
    }

    public static void main(String[] args) {
        // ....stuff
        Collections.sort(scoreList, new CricketSort("IND"));
    }

}

应该管用。

于 2013-06-07T13:23:14.790 回答
0

好的 !有我自己的比较器来做这个

      class CricketSort implements Comparator<CricketLiveScore> 
     { 
        String countryOnTop; 

         public CricketSort(String countryOnTop) { 
                this.countryOnTop = countryOnTop;
       }

      @Override 
      public int compare(CricketLiveScore o1, CricketLiveScore o2) { 
             if (o1.homeAbbrevation.contains(countryOnTop)) {
                  return -1; 
                  } 
             if (o2.homeAbbrevation.contains(countryOnTop)) { 
                  return 1; 
                  } 
           return o1.homeAbbrevation.compareTo(o2.homeAbbrevation);
             } 
         }

    }

它对我来说完美无缺

于 2013-06-10T07:15:23.070 回答
0

您需要一个自定义比较器,例如:http: //java67.blogspot.de/2012/10/how-to-sort-object-in-java-comparator-comparable-example.html

于 2013-06-07T13:03:42.873 回答
0

http://blog.vogella.com/2009/08/04/collections-sort-java/

基本上,您在数据类型中实现 Comparator 接口并覆盖 compare 方法。

于 2013-06-07T13:05:06.597 回答