標籤

二元樹 (1) 字串常數池 (1) 投資 (3) 每月損益 (37) 例外處理 (1) 泛型 (2) 股票 (15) 指標 (5) 英文 (8) 基本資料型別 (1) 期貨 (1) 程式交易 (10) 量化投資 (5) 亂亂寫 (3) 概念 (3) 資料結構 (3) 演算法 (3) 數學 (3) 轉型 (1) AMA (1) ArrayList (1) assert (1) BeautifulSoup (1) C/C++ (8) casting (1) ClassCastException (1) classpath (1) Collection (4) Comparable (1) comparTo() (1) constructor (1) database (3) Debian (1) Dropbox (2) EA (2) enum (1) equals() (2) exception (3) extends (1) ffmpeg (1) final (1) Git (1) HashMap (1) HashSet (1) hasNext() (1) HTS (3) instanceof (1) IS-A (1) Iterator (1) JAVA (43) length (1) Linux (31) List (1) Mac (6) Map (1) ML (2) MT4 (6) MySQL (2) next() (1) NullPointerException (1) Number (1) Numpy (2) OpenCart (1) OpenCV (3) OSX (1) overloading (1) overriding (3) pandas (2) PHP (8) PriorityQueue (1) Python (11) Queue (1) random() (1) reverse() (1) Samba (1) SCJP (21) sqrt() (1) synchronized (1) talib (1) ufw (1) uTorrent (1) var-args (2) VHF (1) vim (2) Yhoo知識+ (4)
顯示具有 SCJP 標籤的文章。 顯示所有文章
顯示具有 SCJP 標籤的文章。 顯示所有文章

2012年10月27日 星期六

HashSet的測試

HashSet實作Set介面,Set介面繼承Collection介面。特性為只有唯一值,而無排序無順序。
未覆寫equals()情況下會測試是否為相同物件後塞入HashSet。

import java.util.*;
public class HashTest{
        String s;
        public HashTest(String s){ this.s = s; }

        public static void main(String[] args){
                HashSet<Object> hs = new HashSet<Object>();
                HashTest ht1 = new HashTest("abcedf");
                HashTest ht2 = new HashTest("abcedf");
                String s1 = new String("abcedf");
                String s2 = new String("abcedf");
                hs.add(ht1);
                hs.add(ht2);
                hs.add(s1);
                hs.add(s2);
                System.out.println(hs.size());
        }
}

==============
3

ht1跟ht2被視為不同物件,而字串s1和s2會被視為相同物件的原因是,String本身就覆寫了equals()的函式。
hs大小為3。

2012年10月26日 星期五

ArrayList的宣告方式

ArrayList:可以動態成長、有快速隨機存取的功能的陣列。

List myList = new ArrayList();    //先寫這樣  
List<String> myList = new ArrayList<String>();  
//再把要加入的物件型別補上,意思就等於String[]

Collection <繼承 List <實作 ArrayList ,Collectionn及List為介面。

equals()和==

equals():值相等
==:指向同一物件


public class EqualsTest{
        public static void main(String[] args){
                String a = "foo";
                String b = "foo";
                String c = new String("foo");
                String d = new String("foo");
                EqualsTest et1 = new EqualsTest();
                EqualsTest et2 = new EqualsTest();

                if(a == b)      System.out.println("Same objects");  //同物件:指向字串常數池的"foo"
                if(a == c)      System.out.println("Same objects");  //不同物件:c的"foo"不在字串池
                else    System.out.println("Different objects");

                if(c == d)      System.out.println("Same objects");  //不同物件
                else    System.out.println("Different objects");

                if(a.equals(b)) System.out.println("Same string");  //回傳true,String有覆寫equals()
                if(a.equals(c)) System.out.println("Same string");  //回傳true,String有覆寫equals()

                if(et1 == et2)  System.out.println("Same objects");  //不同物件
                else    System.out.println("Different objects");

                if(et1.equals(et2))     System.out.println("Same objects");  //不同物件,沒有覆寫equals()

                else    System.out.println("Different objects");


        }
}


==========


Same objects
Different objects
Different objects
Same string
Same string
Different objects
Different objects


2012年10月25日 星期四

參考變數的轉型

class A{}
class B extends A{}
public class CastTest{
        public static void main(String[] args){
                A a = new B();
                B b = (B)new A();    //不能通過IS-A的測試:A IS-A B
                B bb = (B)a;
                a = (A)new B();
        }
}

output:
Exception in thread "main" java.lang.ClassCastException: A
at CastTest.main(CastTest.java:6)

所以可證明物件轉型是看參考變數所指向的物件


==========================

class A{ void showA(){System.out.println("A");} }
class B extends A{ void showB(){System.out.println("B");} }
public class CastTest{
        public static void main(String[] args){
                A a = new B();
                a.showA();
                ((B)a).showB();   //a看不到showB(),必須向下轉型
        }
}

output: 
A
B

method執行看型別,A要執行B的mothed,必須向下轉型成B

覆寫與多載的判斷

覆寫(overriding):
1、基本上要跟原函式一模一樣,包括修飾子、回傳型別及函式名稱,如:
    public void show(){...}
2、可以稍微不一樣的只有修飾子範圍不能小於原修飾子,跟回傳型別可以為原型別的子型別。
3、你不可以覆寫標示為final、static的函式。但可以重新定義標示為static的函式(各自定義)
4、若你不能繼承該函式,你就不能覆寫它。
5、不能宣告原函式沒有宣告的可控式例外。(若父函式沒有宣告可控式例外,則表示它可能丟出任何Exception;所以子函式可宣告任何在Exception內的例外,但不含自定義的例外)

多載(overloading):
1、必須變更參數。(光這項就能抓出一堆偽覆寫函式了)
2、可變更回傳型別。
3、可變更修飾子。
4、可宣告新的或範圍更大的可控式異常。

關於列舉的成員存取

1、enum其實是一個static的類別。
2、在class內的enum就等於是其內部的靜態類別。(inner class)
3、enum內的元素皆為static的String物件。

所以在類別外要存取一個類別內之enum成員,必須當做static類別的static成員來看待:
OuterClass.enumName.enumElement

class Foo{ public enum Direction{ NORTH, SOUTH,  EAST, WEST }}
public class Bar{ Foo.Direction d = Foo.Direction.NORTH; }

2012年10月24日 星期三

javac編譯時選項

-d
指定編譯時class檔存放路徑
javac -d mydir source/MyClass.java    //MyClass.class會存放到mydir目錄裡

-cp 或 -classpath
執行時搜尋class檔的路徑
-cp /dirA:/dirB:.     //以冒號分開不同目錄,句點為目前所在目錄
若編譯時需要用到其他存放在jar檔的class時,需指定class所在目錄或jar檔:
javac -classpath /foo/myLib.jar Book.java

jar檔預設目錄為 $/JAVA_HOME/jre/lib/ext

2012年10月23日 星期二

重要單字

encapsulate     [ɪnˋkæpsə͵let]    封裝

demonstrate    [ˋdɛmən͵stret]    證明;顯示


polymorphism     [͵pɑlɪˋmɔrfɪzm]    多型


suggest    建議


expend    秏盡


effort    [ˋɛfɚt]    盡力


toward    [təˋwɔrd]    朝、向


exhibit    [ɪgˋzɪbɪt]   展示


environment     [ɪnˋvaɪrənmənt]     環境


eligible    [ˋɛlɪdʒəb!]    有資格的


invocation     [͵ɪnvəˋkeʃən]    調用


outcome    [ˋaʊt͵kʌm]     結果


represent    [͵rɛprɪˋzɛnt]    描繪、表現


qualified    [ˋkwɑlə͵faɪd]    合格的、勝任的


indicate    [ˋɪndə͵ket]    指示; 指出


assure    保證


guaranteed    [ˋgærənˋtid]    肯定的


instead     [ɪnˋstɛd]     作為替代


candidate    [ˋkændədet]    候補者[(+for)]


separate    [ˋsɛprɪt]    個別的, 不同的


coupling    [ˋkʌplɪŋ]    耦合    低耦合,即不要跟其它有太多關聨
cohesion    [koˋhiʒən]     內聚     高內聚,功能單一

2012年10月22日 星期一

繼承後的成員變數

class Father{
        int money = 500;
        void spendMoney(int n){
                money -= n;
                System.out.println("Father spend " +n+ ",remain " +money);
        }
}
class Son extends Father{ }

public class Money{
        public static void main(String[] args){
                Father father = new Father();
                Son son = new Son();

                System.out.print("Before father spend money, son has ");
                System.out.println(son.money+ ".");
                father.spendMoney(250);
                System.out.print("After father spend money, son has ");
                System.out.println(son.money+ ".");
        }
}


output:
Before father spend money, son has 500.
Father spend 250,remain 250
After father spend money, son has 500.
自父類別繼承而來的實體變數,會變成自己的實體變數,與父類別無關。

========================================================


class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}
class Son extends Father{
        void spendMoney(int n){
                money -= n;
                super.spendMoney(n);    //這裡呼叫父函式來用,並不是用父物件去呼叫函式
        }
}

public class Money2{
        public static void main(String[] args){
                Father father = new Father();
                Son son = new Son();

                System.out.print("Before son spend money, son has ");
                System.out.println(son.money+ ".");
                son.spendMoney(250);
                System.out.print("After son spend money, son has ");
                System.out.println(son.money+ ".");
                System.out.println("Father has " +father.money);
        }


output:
Before son spend money, son has 500.
After son spend money, son has 0.
Father has 500
呼叫super.spendMoney(n)的意思是,Son物件呼叫父函式(spendMoney())來改變本身value的值,並不是叫Father物件呼叫自已的spendMoney()。因此父物件的value的值並不會變成250。


==================================================



class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}      
class Son extends Father{
        void spendMoney(int n){ super.spendMoney(n); }
        int getMoney(){ return super.money; }
}
           
public class Money2{
        public static void main(String[] args){;
                Son son = new Son();
             
                System.out.print("Before son spend money, he has ");
                System.out.println(son.money+ ".");
                son.spendMoney(250);
                System.out.print("After son spend money, he has ");
                System.out.println(son.getMoney()+ ".");
        }
}

output:

Before son spend money, he has 500.
After son spend money, he has 250.

這裡Son類別內的方法全是存取自Father類別內的方法,仍可正常運作,不會因沒有Father實體而不能存取其實體成員;所以應該可以這樣想:Son類別繼承了Father的field:money、spendMoney(),雖然在Son把spendMoney()給覆寫了,但在呼叫super.spendMoney()時,在編譯器眼裡其實是長這樣:spendMoney(250){ money -=250;}

所以我可以大膽的說,在Son繼承父類別時,在Son裡的spendMoney方法其實有兩個:
void spendMoney(int n){ money -= n; } 跟 void spendMoney(int n){ super.spendMoney(n); }
當呼叫super.spendMoney(n)時,就是呼叫自己的spendMoney(int n){ money -= n; }。
至於為什麼可以這樣想呢?因為啊,就Father類別在程式碼內沒有建立實體啊,所以它的spendMoney()根本不存在啊。Son因為繼承了Father,而且又建立了實體,所以當呼叫super.spendMoney()時,其實就是在跟編譯器說:“嘿,幫我跑一下spendMoney函式,不是跑我覆寫的那一個,是我老爸留給我的那一個spendMoney喔!謝謝!“

====================================================


class Father{
        int money = 500;
        void spendMoney(int n){ money -= n; }
}
class Son extends Father{
        int money = 250;
        void spendMoney(int n){ super.spendMoney(n); }
        void getFathersMoney(Father f){ money = f.money; }
}

public class Money3{
        public static void main(String[] args){;
                Son son = new Son();

                System.out.println("Son has " +son.money+ ".");
                son.getFathersMoney(son);
                System.out.println("Son has " +son.money+ ".");
        }
}



output:

Son has 250.
Son has 500.
這段程式碼是說,兒子偽裝成爸爸去銀行提爸爸的錢。

synchronized


  • 只有函式或區塊可以標上synchronized
    public synchronized void go(){ //code }    //函式
    pubic void go(){ synchronized(this){ //code } }    //區塊
  • 區塊標示法為 synchronized(物件)或synchronized(類別.class)
    synchronized(o)
    synchronized(this)
    synchronized(MyClass.class)

日期格式


  • java.util.Date:
    Date d = new Date();    //建立目前時間的實體
  • java.util.Calender:Calendar為抽象類別,須用靜態函式建立物件
    Calendar c = new Calendar.getInstance();
    c.setTime(d);    //將Date物件指派給c物件
    d = c.getTime();    //將Calendar物件c所設定的時間指派給Date物件d
  • java.util.DateFormat:DateFormat為抽象類別,須用靜態函式建立物件
    DateFormat df = DateFormat.getInstance();
  • java.util.Locale:
    Locale loc = Locale.getDefault();    //取設當地預設格式

2012年10月21日 星期日

關於static


  1. static 函式或變數是屬於類別,被JVM載入時即存在;在物件生成前即存在。
  2. static 函式可透過類別或繼承直接呼叫,或是可用參考變數呼叫:
    class Foo{ static int count = 5; }
    class Abc extends Foo{
        public static void main(String[] args){
            Foo f = new Foo();
            System.out.println(count);
            System.out.println(Foo.count);  
            System.out.println(f.count);    //編譯器是看f的型別(Foo)來呼叫static成員
        }
    }
    //輸出皆為5
  3. static 函式不能存取實體變數或函式(即非static之實體成員)。
  4. static 函式不能被覆寫(overriding)。

函式配對

void go(long n){ System.out.println("long"); }
void go(double n){ System.out.println("double"); }
void go(Integer n){ System.out.println("Integer"); }

int i = 5;
go(5);


output: long

1、函式會依下列參數型別的順序尋找最適合之配對函式:
widening > autoboxing > var-args

2、其中widening(基本資料放寬)會依下列參數型別順序尋找配對:
byte > short > int > long > float > double

3、其中autoboxing(自動包裝成wrapper物件)如下:
boolean --> Boolean
byte --> Byte
short --> Short
char --> Character
int --> Integer
long --> Long
float --> Float
double --> Double

*基本資料可放寬,但wrapper物件不能放寬。Integer無法放寬成Long
void go(Long n){ System.out.println("Long"); }
go(new Integer(5));      //不會放寬

2012年10月17日 星期三

Modifier的可視範圍

private        class

default        class package


protected      class package extends


pubic          any




存取其class成員:
private     同一class裡
default     承上或同一package裡
protected  承上或繼承
public      皆可

2012年10月1日 星期一

toString測試


public class ToStringTest{
public static void main(String[] args){
String x = "big surprise";
int[] y = {1,3};
ToStringTest z = new ToStringTest();

System.out.println(x.toString()+ "\n" +y.toString()+ "\n" +z.toString());
}
}



$ java ToStringTest
big surprise
[I@9b49e6
ToStringTest@10d448



2012年9月29日 星期六

exception測試2

class BadFoodException extends Exception{ }
public class MyException{
    static String[] food = {"Apple", "Banana", "Cocoa", "Coffee", "Toast"};

    public static void main(String[] args){
        try{
            checkFood(args[0]);
        }catch(BadFoodException e){
            System.out.println("I don't like.");
        }
    }
   
    static void checkFood(String input) throws BadFoodException{
        int flag = 0;
        for(String s : food){
            if(s.equals(input)){
                flag = 1;
                break;
            }
        }
        if(flag == 1)    System.out.println("I like it.");
        else throw new BadFoodException();
    }
}



==================================
$ java MyException Toast
I don't like.

$ java MyException Apple
I like it.

2012年9月27日 星期四

exception測試

class Propagate{
    public static void main(String[] args){
        try{
            System.out.println(new Propagate().reverse(""));
        }catch(ArithmeticException e){
            System.out.println("Input error!");
        }finally{
            System.out.println("The main method is done.");
        }
    }
   
    String reverse(String s){
        String reverseStr = "";
       
        if(s.length() == 0)    throw new ArithmeticException();
        else{
            for(int i=s.length()-1; i>=0; --i){
                reverseStr += s.charAt(i);
            }
        }
        return reverseStr;
    }
}



===========
reverse("Hello")
olleH
The main method is done.


reverse("")
Input error!
The main method is done.

例外是隨便挑一個做throw

2012年9月24日 星期一

列舉多載method

public class Bridge{
    public enum Suits{
        CLUBE(20), DIAMONDS(20), HEARTS(30), SPADES(30),
        NOTRUMP(40){
            public int getValue(int bid){
                return (bid - 1) * 30 + 40;
            }
        };
       
        Suits(int points){
            this.points = points;
        }
       
        private int points;
       
        public int getValue(int bid){
            return points * bid;
        }
    }
   
    public static void main(String[] args){
        System.out.println(Suits.NOTRUMP.getValue(3));
        System.out.println(Suits.SPADES + " " + Suits.SPADES.points);
        System.out.println(Suits.values());
    }
}



=========================
100
SPADES 30
[LBridge$Suits;@4a65e0

2012年9月17日 星期一

instanceof測試

class Animal{
    public void testIsA(Animal a){
        System.out.println("Animal");
    }
}
class Dog extends Animal{
    public void testIsA(Animal a){    //a是Animal的參考
        System.out.println(a instanceof Animal);    //但instanceof會看a的物件型別
        System.out.println(a instanceof Dog);
        //a.show();            //此行會產生錯誤,因為a的型別為Animal,而該class無show函式
    }
    public void show(){
        System.out.println("I am class Dog");
    }
}

public class InstanceOfTest{
    public static void main(String[] args){
        Animal dog1 = new Animal();
        Animal dog2 = new Dog();
        Dog dog3 = new Dog();
       
        System.out.println(dog1 instanceof Animal);        //true; Animal IS-A Animal
        System.out.println(dog1 instanceof Dog);        //false; Animal IS-A Dog
        System.out.println(dog2 instanceof Animal);        //true; Dog IS-A Animal
        System.out.println(dog2 instanceof Dog);        //true; Dog IS-A Dog
        System.out.println(dog3 instanceof Animal);        //true; Dog IS-A Dog
       
        dog1.testIsA(dog1);        //Animal,*****
        dog1.testIsA(dog2);        //Animal,overriding取決於呼叫的物件
        dog1.testIsA(dog3);        //Animal,*****
       
        dog1.testIsA(dog1);        //Animal,overriding取決於呼叫的物件
        dog2.testIsA(dog2);        //true, Dog IS-A Animal
                                //true, Dog IS-A Dog
        dog3.testIsA(dog3);        //true,true,
    }
}

======
結論:
1・父類別物件可以呼叫子類別函式(通常父類別看不見子類別內的成員),但只限於被子類別overriding過的函式。
2・不管傳入函式的引數為何,皆以函式之參數的型別宣告為準。
3・而instanceof會去看參考所指向的物件,並以該物件為準。

2012年9月16日 星期日

父類別函式覆寫

 父類別參考指向子類別物件,執行被覆寫之函式

class GameShape{
    public void display(){
        System.out.println("GameShape");
    }
    public void motion(){
        System.out.println("Motion");
    }
}

public class Player1 extends GameShape{
    public void display(){
        System.out.println("Player1");
    }
    public void show(){
        System.out.println("show");
    }
    public void showDad(){
        super.display();
    }
   
    public static void main(String[] args){
        GameShape game = new Player1();
        Player1 player = new Player1();
       
        game.display();
        player.display();
       
        game.motion();
        player.motion();
       
        player.showDad();
        player.show();
    }
}














====================
Player1
Player1
Motion
Motion
GameShape
show