//ts5.java 用 List做 Stack --- by tsaiwn@csie.nctu.edu.tw import java.util.*; class MyStack extends ArrayList{ /////////////////// 原則: Data 藏起來, functions 公開 public MyStack( ) { super( ); } // synchronized public void push(Object o) { add(o); } synchronized public Object peek( ) { return get(size( )-1 ); } // C++ 叫做 top( ) synchronized public Object pop( ) { int last = size( ) - 1; Object tmp = get( last ); remove( last ); return tmp; } public boolean empty( ) { return isEmpty( ); } public boolean full( ) { return false; } } // MyStack // Note that the Stack in Library is made of Vector class ts5 { static double x[ ] = {1,21,23,24,5,8,22,2,3,4,25,28}; public static void testaa( ) { MyStack ss = new MyStack( ); for(double y:x) { System.out.print(y+" "); ss.push(y); // JDK 1.5 後會 autoBoxing } // for System.out.println("\n=== now check stack ..."); while( !ss.empty( ) ) { System.out.print(""+ ss.pop( ) + " "); } System.out.println(); } ////// use Library Stack // 注意 testaa( ) 與 testbb( ) 完全相同! public static void testbb( ) { Stack ss = new Stack( ); // 除了這裡用程式庫的 Stack for(double y:x) { System.out.print(y+" "); ss.push(y); // JDK1.4.x 以前不可以! } // for System.out.println("\n=== now check stack ..."); while( !ss.empty( ) ) { System.out.print(""+ ss.pop( ) + " "); } System.out.println(); } public static void main( String xx[]) { testaa( ); println("===Now using Library Stack..."); testbb( ); println("==="); Arrays.sort(x); for(double y:x) System.out.print(y+" "); println(""); Double dx[ ] = new Double[x.length]; for(int i=0; i < x.length; ++i) Arrays.fill(dx, i, i+1, new Double(x[i])); println("====== dx.length=" + dx.length); for(Double y:dx) System.out.print(y+" "); println(""); GG g = new GG( ); Arrays.sort(dx, g); for(Double y:dx) System.out.print(y+" "); println(""); } // main static void println(String s){System.out.println(s);} } // class ts5 class GG implements Comparator { public int compare(Object x, Object y) { if(x==null) return 1; if(y==null)return -1; Double xx = (Double)x; Double yy=(Double)y; double ans = yy - xx; // auto unboxing if(ans==0) return 0; return ans>0? 1: -1; } }