Java麵向對象高級--繼承的應用----整形數組類、排序類、反轉類

分析:

class Array{ // 表示數組
private int temp[] ; // 整型數組
private int foot ; // 定義添加位置
public Array(int len){
if(len>0){
this.temp = new int[len] ;
}else{
this.temp = new int[1] ; // 最少維持空間是1個
}
}
public boolean add(int i){ // 增加元素
if(this.foot<this.temp.length){ // 還有空間
this.temp[foot] = i ; // 增加元素
this.foot ++ ;// 修改腳標
return true ;
}else{
return false ;
}
}
public int[] getArray(){
return this.temp ;
}
};
class SortArray extends Array{ // 排序類
public SortArray(int len){
super(len) ;
}
public int[] getArray(){ // 覆寫方法
java.util.Arrays.sort(super.getArray()) ; // 排序操作
return super.getArray() ;
}
};
class ReverseArray extends Array{ // 反轉操作類
public ReverseArray(int len){
super(len) ;
}
public int[] getArray() {
int t[] = new int[super.getArray().length] ; // 開辟一個新的數組
int count = t.length - 1 ;
for(int x=0 ;x<t.length;x++){
t[count] = super.getArray()[x] ; // 數組反轉
count-- ;
}
return t ;
}
};
public class ArrayDemo{
public static void main(String args[]){
// ReverseArray a = null ; // 聲明反轉類對象
// a = new ReverseArray(5) ; // 開辟5個空間大小
SortArray a = null ;
a = new SortArray(5) ;
System.out.print(a.add(23) + "\t") ;
System.out.print(a.add(21) + "\t") ;
System.out.print(a.add(2) + "\t") ;
System.out.print(a.add(42) + "\t") ;
System.out.print(a.add(5) + "\t") ;
System.out.print(a.add(6) + "\t") ;
print(a.getArray()) ;
}
public static void print(int i[]){ // 輸出數組內容
for(int x=0;x<i.length;x++){
System.out.print(i[x] + "、") ;
}
}
};
最後更新:2017-04-03 15:21:46