自定义方法实现ArrayList排序

 1 package cn.edu.nwpu.java;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Collections;
 7 
 8 public class MyScore {
 9 
10     public static void main(String[] args) {
11         // 实现选择、排序、求平均的问题
12         // java的数组是定长的,要想实现可编程的数组需用集合类ArrayList或者vector
13         // 两者的区别是vector是同步的,但是ArrayList是异步的,这个只在多线程中会遇到,异步更快,同步更安全
14         ArrayList<Double> scores = new ArrayList<>();
15         // .add()方法用于向Arraylist中添加数据
16         scores.add(80.0);
17         scores.add(68.9);
18         scores.add(70.8);
19         scores.add(90.4);
20         System.out.println("最高的分数是:" + MyScore.highestScore(scores));
21         for(int i = 0; i < scores.size(); i++) {
22             System.out.println(scores.get(i));
23         }
24     }
25     
26     /**
27      * 用于对成绩进行排序,然后返回最大值,顺利实现自定义的集合排序
28      * @param ds 带排序的数组
29      * @return 返回最大值
30      */
31     public static double highestScore(ArrayList<Double> ds) {
32         for(int i = 0; i < ds.size(); i++) {
33             for(int j = i+1; j < ds.size(); j++) {
34                 if (ds.get(j) > ds.get(i)) {
35                     double temp;
36                     temp = ds.get(j);
37                     ds.set(j, ds.get(i));
38                     ds.set(i,temp);
39                 }
40             }
41         }
42         return ds.get(0);
43     }
44 
45 }
原文地址:https://www.cnblogs.com/wsg25/p/7529216.html