【问题标题】:Array List Sorting [duplicate]数组列表排序[重复]
【发布时间】:2011-01-07 03:04:26
【问题描述】:

您将如何按字母或数字对ArrayList 进行排序?我不太确定按字母顺序或数字顺序对数组进行排序的方法将如何工作。

谢谢!

【问题讨论】:

  • 完全不清楚您在寻找什么。请详细说明。举例说明问题

标签: java sorting


【解决方案1】:

[Collections.sort][1] 将默认排序。这对于字符串是词汇(字母),对于数字数据类型是数字。如果您需要非标准排序,也可以指定自己的比较器。

例如:

ArrayList list = new ArrayList();
list.add(1);
list.add(10);
list.add(-1);
list.add(5);

Collections.sort( list );

[1]:http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,java.util.Comparator)

【讨论】:

  • 您可能会问如何实现这样的排序机制,但这通常不是您在商业世界中想要做的;)。如果这是家庭作业,请将其标记为更具体。
【解决方案2】:

Collections.sort 方法允许使用实现特定排序方法(例如字母或数字排序)的 Comparator 对列表进行排序。

【讨论】:

    【解决方案3】:
    Collections.sort(list,new Comparator() { 
    
        int compare(T o1, T o2) {
            // implement your own logic here
        }
    
    
        boolean equals(Object obj) {
            // implement your own logic here
        }
    }
    

    【讨论】:

      【解决方案4】:

      一般使用Collections.sort()方法对简单的数组列表进行排序。

      这是一个例子。

      首先实现Comparable接口,然后重写compareTo方法。

      public class Student implements Comparable {
          private String studentname;
          private int rollno;
          private int studentage;
      
          public Student(int rollno, String studentname, int studentage) {
              this.rollno = rollno;
              this.studentname = studentname;
              this.studentage = studentage;
          }
      
          @Override
          public int compareTo(Student comparestu) {
              int compareage=((Student)comparestu).getStudentage();
          }
      
          @Override
          public String toString() {
              return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
          }
      
      }
      

      现在我们可以很好地在 ArrayList 上调用Collections.sort

      import java.util.*;
      public class ArrayListSorting  {
      
          public static void main(String args[]){
             ArrayList<Student> arraylist = new ArrayList<Student>();
             arraylist.add(new Student(100, "Nuwan", 19));
             arraylist.add(new Student(200, "Kamal", 18));
             arraylist.add(new Student(205, "Sunil", 20));
      
             Collections.sort(arraylist);
      
             for(Student str: arraylist){
                  System.out.println(str);
             }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        • 2018-12-08
        • 2017-02-12
        • 1970-01-01
        相关资源
        最近更新 更多