public class IntList {
private int[] data;
private int currentSize;
private int maxSize; public IntList() {
currentSize = 0;
maxSize = 10;

} public IntList(int size) {
currentSize = 0;
maxSize = size;
data = new int[maxSize];
} public int getCurrentSize() {
return currentSize;
} public void addToList(int a) {
if (currentSize < maxSize)
data[currentSize++] = a;
else
System.out.println("Can not add element");
} public int search(int a) {
for (int i = 0; i < maxSize; i++) {
if (data[i] == a)
return i;
}
return -1;
} public int elementAt(int i) throws IndexOutOfBoundsException {
if (i < 0 || i > maxSize)
throw new IndexOutOfBoundsException();
return data[i];
} public void clear() {
data = new int[maxSize];
currentSize = 0;
} public String toString() {
String temp = "[";
for (int i = 0; i < currentSize-1; i++) {
temp += data[i] + ",";
}
temp += data[currentSize-1] + "]"; return temp;
}}写一个SortedList 要求把public void addToList(int a)重写,添加时要按从小到大的顺序.

解决方案 »

  1.   

    // 创建一个继承自IntList类的类SortedList
    class SortedList extends IntList {    // 重写(添加时要按从小到大的顺序) (int data[]的private改成protected)
        public void addToList(int a) {
            if (currentSize < maxSize) 
                super.data[currentSize++] = a; 
            else 
                System.out.println("Can not add element"); 
        }
    }