zoukankan      html  css  js  c++  java
  • Java泛型——对一个对象数组进行排序

    Java泛型——对一个对象数组进行排序

    public class GenericSort {
         
        public static void show() {
            Integer[] intArray = {new Integer(2),new Integer(4),new Integer(3)};
            Double[] doubleArray = {new Double(2.5),new Double(6.4),new Double(3.3)};
            Character[] charArray = {new Character('a'),new Character('q'),new Character('c')};
            String[] stringArray = {"liu","lu","hhh"};
         
            sort(intArray);
            sort(doubleArray);
            sort(charArray);
            sort(stringArray);
             
            System.out.print("sorted integer objects: ");
            printList(intArray);
            System.out.print("sorted Double objects:  ");
            printList(doubleArray);
            System.out.print("sorted char objects:   ");
            printList(charArray);
            System.out.print("sorted string objects:  ");
            printList(stringArray);
             
        }
         
        public static <E extends Comparable<E>> void sort(E[] list) {  //可以对任何对象类型的数组进行排序
            E currentMin;
            int currentMinIndex;
             
            for(int i = 0; i < list.length -1 ;i++) {
                currentMin = list[i];
                currentMinIndex = i;
                for (int j = i+1 ; j < list.length; j++) {
                    if(currentMin.compareTo(list[j])>0) {
                        currentMin = list[j];
                        currentMinIndex = j;
                    }
                }
                 
                if(currentMinIndex != i) {
                    list[currentMinIndex] = list[i];
                    list[i] = currentMin;
                }
            }
        }
         
        public static void printList(Object[] list) {
            for(int i = 0; i< list.length ; i++)
                System.out.print(list[i]+" ");
            System.out.println();
        }
    }
    

      

  • 相关阅读:
    ctypes运用
    win10 下获取不到
    semantic ui加载慢的问题
    python 将图片转换为base64编码转储进数据库
    循环遍历共享文件夹,不需要知道目录深度拷贝上传
    计划和打算
    pyqt按键检测
    python B+数的实现
    JAVA算数运算符
    ASCLL码表
  • 原文地址:https://www.cnblogs.com/Bluebells/p/14290918.html
Copyright © 2011-2022 走看看