实现MyArrayList 要求实现add方法、sort方法(两个、正向排序、逆向排序)

如题所述

package test;

import java.util.*;
public class test {
    public static void main(String[] args) throws Exception {

        MyArrayList myArrayList = new MyArrayList();
        myArrayList.add(79);
        myArrayList.add(23);
        myArrayList.add(56);
        myArrayList.add(5);
        for (int i : myArrayList.arr) {
            System.out.println(i);
        }
        myArrayList.sort();
        System.out.println("---升序---");
        for (int i : myArrayList.arr) {
            System.out.println(i);
        }
        myArrayList.sortDesc();
        System.out.println("---降序---");
        for (int i : myArrayList.arr) {
            System.out.println(i);
        }
    }
}

class MyArrayList {
    int index = 0;
    int[] arr = null;
    public boolean add(Integer i) {
        int[] temp = new int[++index];
        if (arr != null) {
            System.arraycopy(arr,0,temp,0,arr.length);
        }
        arr = temp;
        arr[index-1] = i;
        return true;
    }
    public boolean sort(){
        if (arr != null) {
            Arrays.sort(arr);
            return true;
        }
        return false;
    }
    public boolean sortDesc(){
        if (arr != null) {
            Arrays.sort(arr);
            int[] temp = new int[index];
            int tempIndex = 0;
            for (int i = index-1; i >-1; i--) {
                temp[tempIndex++] = arr[i];
            }
            arr = temp;
            return true;
        }
        return false;
    }
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-04-04
简单的方式是继承ArrayList类,实现add方法,然后自定义两个排序方法,内部可以用equals比较。
比较复杂的方式是底层和ArrayList一样,封装一个数组,最好采用泛型。依次实现以上的几个的方法。
时间有限就不一一写了