程式碼高𠅙

2014/03/27

Java Practice: Shutdown Hook

今日 Daily Java Practice 如下,請問其中 runTime.addShutdownHook 的作用。

public class Main implements Runnable {
    public void run() {
        System.out.println("Shutting down");
    }

    public static void main(String[] arg) {
        Runtime runTime = Runtime.getRuntime();
        Main hook = new Main();
        runTime.addShutdownHook(new Thread(hook));
    }
}

2014/03/24

Java Practice: Enum

今天來玩玩 enum, 以下透過一程式,說明 enum 如何把物件導向程式的三個特質封裝、繼承跟多型完美的結合在一起。
善用 enum,可以大幅減少程式碼。
以下請說明:
  • 程式輸出訊息。
  • 為何輸出此訊息。
  • S, M, L, XL ... 與 Size 的關係,是類別跟實體的關係,還是父類別跟子類別的關係?

public class SizeIterator {
    public static void main(String[] args) {
        Size[] sizes = Size.values();
        for (Size s : sizes) {
            s.showName();
            s.showType();
        }
    }
}

enum Size {
    S {
        @Override
        public void showName(){
            System.out.println("I am too small to show to others!");
        }
    }, M, L, XL, XXL, XXXL;
    public void showName() {
        System.out.println(this.name());
    }
    public void showType() {
        System.out.println(this.getClass().getName());
    }
}

2014/03/19

Java Practice: Object Serialization

今天的 Java Practice 如下, 請服用:
  1. Coper 類別的功用為何?
  2. Coper:: <T> copyInstance(T obj) 方法使用了 Java Generic 的技巧,請解釋這裡採用型別參數的好處?
  3. main 方法中印出的兩個 User 物件,內容是否相同? 若有差異,原因為何?
abstract class Copier {
    @SuppressWarnings("unchecked")
    public static <T> copyInstance(T obj) throws IOException,
            ClassNotFoundException {
        ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        ObjectOutputStream outStream = new ObjectOutputStream(outBytes);
        outStream.writeObject(obj);
        outStream.close();
        ByteArrayInputStream inBytes = new ByteArrayInputStream(outBytes
                .toByteArray());
        ObjectInputStream inStream = new ObjectInputStream(inBytes);
        T copied = (T) inStream.readObject();
        inStream.close();
        return copied;
    }
}

class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private Date date = new Date();
    private String username;

    private transient String password;

    public User(String name, String pwd) {
        username = name;
        password = pwd;
    }

    public String toString() {
        String pwd = (password == null) ? "(n/a)" : password;
        return "logon info: \n   username: " + username 
            + "\n   date: " + date
            + "\n   password: " + pwd;
    }
}

public class CopierTest {
    /**
     * @param args
     * @throws Exception
     * @throws IOException
     */
    public static void main(String[] args) throws Exception {
        User jack = new User("Jack", "magic");
        System.out.println(jack);
        User copyOfJack = Copier.copyInstance(jack);
        System.out.println(copyOfJack);
    }
}  

2014/03/18

Java Practice: Random


練習一下使用 Java Random 類別。
以下題目,請試著寫出最後 min, max 印出來的最可能數值。
public class MathRandomTest {
 public static void main(String[] args) {
    Random rand = new Random();
   
   int n = 10;
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
   
    for(int i = 0; i < 100; i ++){
      int r = rand.nextInt(n + 1);
      min = Math.min(min, r);
      max = Math.max(max, r);
    }
    System.out.printf("Min = %d, Max = %d", min, max);
 }
}  

2014/03/17

Java Practice: Generics

從今天開始,預計把發給敝公司新人的 Java Practice 題目,release 在此給大家參考。Java 的初學者可以試著練習看看,老手也可溫故知新喔!

首先是 Java Generics 之應用,請在 ________ 填入正確宣告,使程式可以正常運作:
class TwoTypeParas <T,V> {
    T ob1;
    V ob2;

    TwoTypeParas(T o1, V o2) {
        ob1 = o1;
        ob2 = o2;
    }

    void showTypes() {
        System.out.println("Type of T is " + ob1.getClass().getName());
        System.out.println("Type of V is " + ob2.getClass().getName());
    }

    T getob1() {
        return ob1;
    }

    V getob2() {
        return ob2;
    }
}

public class TwoTypeParaTest {
    public static void main(String args[]) {
        TwoTypeParas______ tgObj = new TwoTypeParas______(88, "Generics");
        tgObj.showTypes();

        int v = tgObj.getob1();
        System.out.println("value: " + v);

        String str = tgObj.getob2();
        System.out.println("value: " + str);
    }
}