Download GarfieldSCJPnote

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
-1-
合法的程式進入點(Main)與命名規則:

命名規則為大小寫區分,需以”英文字母”或”_”或”$”開頭

main() method 可以宣告為 final,這樣是 overloading 的 main()。

main() method 不可呼叫 non-static method 及成員,可以丟出 Exception。

格式須為: public static void main(String[] args / String []args / String args[]) {}

class 中如果沒有合法的 main method,在 compile 時不會有錯,但在 run-time 時會產生錯誤。

method 的回傳型態必須在 access modify 之後。
Java keywords:(只要是 keyword,必定是小寫)

boolean、char、byte、short、int、long、float、double

if、else、switch、break、continue、return、case、do、while、for、goto、const

new、this、super、void、class、extends、import、package、implements、instanceof、interface

try、catch、finally、throw、throws

public、private、protected、default、final、abstract、static

native、strictfp、synchronized、transient、volatile
Data Type 範圍及初始值:
char
'\u0000'
16
’\u0000’ ~ ‘\uFFFF’
byte
0
8
-27 ~ 27-1
-128 ~ 127
short
0
16
-215 ~ 215-1
-32768 ~ 32767
int
0
32
-2
long
0L
64
-263 ~ 263-1
float
0.0F
32
double
0.0D
64
boolean
false
1
所有參考型別
null
31 ~
*
0 ~ 65535
2 -1
31
true / false
*某個特定的 Unicode character,其中\u????是 16 進制的數字,且一定得是四個,不可多不可少。

char 也可宣告為 0~65535 的數字而不需加上單引號’ (0 或-0 都不會產生錯誤) 。

只要有小數點,一定要宣告成 double(後面可加 D 或 d 也可不加)。

若要宣告為 float,需在數字後加上 f 或 F。(float a=1L;//是合法宣告) 。

合法的跳脫字元【 big foot need red tie 】。

String 類別初始化的預設值為 null 並非為”空的”String(只是尚未賦予 reference),且沒有 quote。

String = “” 和 String = null 意思不同(String a=null;System.out.print(a);//會 print 出”null”) 。

String a=”\uD7AF”;// (?)合法,String b=”\u000a”;//(new line)不合法,String c=”\n”;//合法。
Modifiers:

Access modifiers:

一次最多只能使用一個 access modifier。

若不想讓其他人存取這個 class,將所有的 constructor 宣告為 private 即可。

method 內的 variable 只可用 final 修飾。

修飾 classes / interfaces 只可用(default)或 public。

Access modifiers 列表:
name
public
注意事項
一個 source file 只能有一個 public class,且名稱大小寫需與檔名相符。
proctected
(default)
不是 java 的 access keyword,只是代表了沒有指定任何 access modifier 的情況。
-2繼承後也無法使用,只有本身的 class 可以使用。
private

使用範圍:
Modifier

Class
Variable(class level)
Method
Constructor
FreeFloating Block
public
yes
yes
yes
yes
no
protected
no
yes
yes
yes
no
(default)
yes
yes
yes
yes
yes
private
no
yes
yes
yes
no
可視範圍
class
package
private
Ÿ
default
Ÿ
Ÿ
proctected
Ÿ
Ÿ
public(defalut)
Ÿ
Ÿ
public(public)
Ÿ
Ÿ
sub-class
other-package
Ÿ*
Ÿ
Ÿ
*為當繼承關係存在時。
*記住:subclasses from different packageproctected

;same package(default)
Other modifiers:

Other modifiers 列表:
name
注意事項
可以
method
class
不可以
var

method 被宣告為 static 或 private,即自動為 final。

final method 內的 variables 只能用 final 修飾。

final class 不可被繼承,不能被 overridden。

final var 只能被設定一次,設定後不能被改變。

不可改變 final reference var 去指向另一個 object,但是可
以改變所指向之 object 的狀態。
final
注意


有 final 就不會有 abstract,final class 必須是一個定義完整的 class。

final class 內的所有 methods 都是 final method,不須明示宣告。
blank final variable:
須在 static init 中設定
class var
instance var
local var

觀念
每個 constructor 中設定,若有 overloading contractors,無論那個
constructor 來 instantint 一個 obj,只會被設定一次。
須先設定初值
class諾貝爾獎 method和平獎、物理獎... subclass負責規範與選
出得和平獎人的一群人、負責規範與選出得物理獎人的某學院。

定義一個 method,要強迫 subclass 必須實作的方式即為宣告為 abstract。
class
abstract
可以
method

一般 class 也可以故意宣告成 abstract class。

abstract class 可以有 constractor。

abstract method 宣告可以有 throws。

abstract method 可以 overriden abstract method 或
instance method(not abstract)。
不可以
class

abstract class 內可以有已經實作的方法。
method

abstract method 不可有 method body({})。
-3
other
不可被實體化(instantiate) subclass 可用”super()”呼叫來
初始化這個 abstract class 內所定義的 instance variable。

不可與 private、final 或 static 一起用,也不可跟實作有關的
修飾字連用(synchronized、native、strictfp 等)。
當 class 內宣告了 abstract methods 或當 class extends 自 super

abstract class 或 implements 自 interface 卻未實作時,需宣告該 class
為 abstract class。
注意
extents 一個 abstract class 後,要實作該 class 內的 abstract method

時的 access modify 必須是 public。
class
可以
method
static
不可以
method
other
native

static field 只可定義在 class 層級。

static method 只可以被 subclass 的 static method
“shodawed”。

static method 的 body 內不可以有”this”或”super”。

static method 不可被 non-static method “overridden”

non-static method 也不可以 overridden static method。

static init 於 class load 時就執行,內不可有”return”出現。

主要用於 load the library in to a Java program。

宣告方式與 abstract method 相同(只有 body),差別在於 abstract method 的 body
在 subclass 中,而 native method 的 body 根本不在 JVM 中。

通常建議寫於 static init 的 block 中。System.loadLibrary(“MyNativeLib”);

Transient fields are not serialized

當物件被寫入一持久性區域,該值將不會被儲存。(Class T{ transient int a; int
b; }//a 不會被儲存,但 b 會) 。

例如在進行登入作業的時候,IE 會自動記錄我們的帳號名稱,但密碼欄位則不會,因為
這是屬於敏感性資料,會將其設為 transient,下次登入時需要重新輸入。
transient

通常 EntityBean 會用到 transient 的機會比較多。EB 代表的可能是 DB 裡面的一筆
record,但是當我們沒有 DB,也可以把這個 EB 給 serialize 成一個檔案,存放在任何
地方。這時候,在 EB 裡面被宣告成 transient 的任何 property,在 serialization 的
過程中,會被忽略掉不存。
synchronized
volatile

主要用在 multi-threaded 環境時。

shared between threads, to force each thread to reconcile its own working
copy of the field with the master copy stored in the main memory.

不可與 final 一起使用。

主要用在 multi-processor 環境時。

和 access modifier 配合使用,一次可宣告超過一個的 modifier。

strictfp 可用於 class 及 non-abstract method。

使用範圍:
Modifier
Class
(Top-level)
Class
Variable
Method
Constructor
FreeFloating
Block
final
yes
yes
yes
yes
no
no
abstract
yes
yes
no
yes
no
no
static
no
yes
no
yes
no
yes
-4native
no
no
no
yes
no
no
transient
no
no
yes
no
no
no
volatile
no
no
yes
no
no
no
synchronized
no
no
no
yes
no
yes
各種 variables 比較:
class (static)
local
何時生
當 class 被載入時
當 object 被建立時
當程式進入 local block 時
何時死
當 class 不再被需要時
當 object 不再被參考時
當程式離開 local block 時
一份,所有 instance 共享
每個 instance 都有一份
無此概念
會,當 class 被載入時
會,當 object 被建立時
不會
ClsName.clsVar
objName.instVar
不可於 local 外存取
public、protected、final、
public、protected、private、
final
private、volatile
final、volatile、transient
幾份 copy
init
如何存取
(objName.clsVar 也可以)
modifiers

instance
init block 的執行順序依照宣告時的順序而定
Converting and Casting:

參數傳遞時若為 primitive type,為 call by value,被改變時原值不會被更改;若為 object reference,被改
變時值會被更改,為 call by reference。(Array references are passed by value)

Primitive Types Conversion:

byte → short →

int → long → float → double

char
boolean
【big sunny is large from dark】

char 轉到 byte/short 或反之,都需要做強制轉型。

boolean 不接受任何轉型。

interger 可安全地轉為 floats。

0 → 8 進制 ; 0x → 16 進制。

-0.0 == 0.0 is true。

1.0 / 0.0  “Infinity”;0.0 / 0.0  “NaN”;-1.0 / 0.0  “-Infinity”;1 / 0  “ArithmeticException”

不同型別在做數學運算前,compiler 會自動將小的型別改成大的型別。

int i=1; long j=2; m(float a) ; m(double a);//在 method call 時會自動將型別轉換(int 及 long 可安
全的轉成 float 或 double),當兩個 method 都符合條件時,會以範圍小的為主(即進 m(floatn a))。

在 method call 時,XX z(int a,double b) { ruturn (long)a * b } // XX 需為 double 型態(自動轉型)

int 與 String 的轉換為:Integer.toString() / Integer.parseInt()

所有 operators 中,只有“+”與”+=”是 overloaded operators。

常見轉型:

floating-point types 轉成 integral types
小數點後面直接截掉
integral types 做 harrowing conversion
左邊多餘的 bits 直接截掉
運算子遇到何種運算元時會做轉型的情況與規則:
一個運算子

若 operand 是 byte、short、char 則會轉成 int type,否則維持原 type。
ex:

shif operator:>>、>>>、<<(<<只對左邊的 operand)
byte a=3;

<<:左移到指定位址後,右邊補 0
b=~a; →

>>:有正負數之分,變數為正便右移到指定位址後左邊補 0;為負則右移到指
-5定位址後左邊補 1
b=(byte)(~a)

>>>:無符號右移運算子,右移到指定位址後左邊補 0

plus、minus:+、-

bit-wise:~

~(00001111)  (11110000) (快速計算法:~i = (-i) - 1)

運算元必須是整數資料型態,否則需先做 casting。

increment / decrement:++、-- (compiler 會將運算結果自動轉回原 type)

若其中一個 operand 是 double/float/long,則將另一個自動轉型為同 type,否則
兩者皆改為 int。

*、/、%

其中一個運算子為 float 或 double 對於除以 0 可處理”/、%”,若為 int 或 long
則在 runtime 時會丟出 ArithmeticException。只有除法(/)與求餘數(%)會出
現 Arithmetic Error。

float 或 double 除以 0 得到的是 positive infinity:若該 float 或 double 為負,
則除以 0 後得到 negative infinity。

所以牽涉到 NaN(not a number)和非 NaN(正負無限大)的比較運算
(Float.isNaN(float) or Double.isNaN(double)),一律回傳 false。
兩個運算子
ex:

正負無限大(Infinity)比較時,Infinity == Infinity // true。
byte a=1;

a % b,當 a 為負時,求得的值為負,不需管 b 的正負。
byte b=2;

addition、subraction:+、-
byte c=a+b;

numerical comparison:<、<=、>、>=、==、!=
→ byte c =

integer bitwise:&、^、|
(byte)a+b)

當三者同時出現時,注意執行順序為 &  ^  | 。

&&、||是指 short-circuit logical operator,即左側算式會被先估算,若已能
產生決定結果,就不估算右側的算式(&&左側結果為 true 或||左側結果為 false
時才會繼續算右側算式)。


ternary operator: a = x ? b : c

x 須為 boolean,是對 b、c 做轉型。

a = b ? c : d ? e : f //執行順序為由右向左(d ? e : f 會先被執行)

int x=4;println((x>4)?99.99:8);8.0(若 99.99 是 99,則印出 8)
compound assignment operators:+=….(對其 oper 做轉型,結果再轉回原型)


ex:byte a=1;
a+=1.9; //這行會自動改為 a=(byte)(a+1.9);
Referenct Types Conversion:

除非有繼承關係存在,否則不可轉型。(「兄弟類別」
(同一父類別)無法做型別轉換)

父類別轉型為子類別時,compile 不會出現錯誤,但 runtime 時會 error。

interface 要做轉型時需明確告知型別。

instanceof 是用來判斷某物件屬於何種類別物件的運運算元。(String s=”ABC”; boolean flg = s
instanceof String;//flg=true)instanceof 的左邊通常是任何 object reference expression 或
variable,但右邊必須是與左邊有繼承關係的 class, interface, 或 array type,否則會發生 error。

Reference type 與 primitive type 是不可以做 casting 的。

合法宣告:Father F = new Son();

Son S = new Father();
F = S;
F 只看得到 Father 的 method 和 property,看不到 Son 的。
S = (Son)F;
-6-
equals()與==:
比較物件內容
比較是否同一物件
equals()
String
String
String
String
String
str1
str2
str3
str4
str5
==
=
=
=
=
=
new String(“abc”);
new String(“abc”);
str1;
“abc”;
“abc”;
str1 / str2
str1 / str3
str4 / str5
str1 / str4
Equals
true
true
true
true
==
false
true
true
False

String str = "abc" 跟 String str = new String("abc")在做”==”得到的結果不同。

long i = 1; double j = 1;

Long a = new Long(3L); Long b = new Long(3L); Double x = new Double(3.0); //a == b 為 false(因
// i == j 為 true。(因為 primitive data type,值相等即為 true)
為 reference type,非同一個物件了)。//a == x 為 compile err(因 a 與 x 無繼承關係無法 convertible)

==的左右兩邊若為不相容的型別轉換,則會發生 compiler errors,但若是 equals,當物件不相同時 equal()
會回傳 false,不會造成編譯錯誤(equals Float object and Double object will always return false)。

compares(equals) a Float object and a Double object which will always return false。

每個 java class 都有一個”equals()”method,這個 method 是使用”==”來比較兩個 reference var 所存的值
(即是否指向一物件)若要比較 content 是否相同,必須 override equals() method,同時也必須 override 定
義於 Object class 的”hashcode()”method,否則 java collection API 操作這個 class 的 object 時會錯。

String、Date、File 及 8 個 wrapper classes 都已 override equals() method。

如果 hashCode 值相同,那 object”可能”相同(equal);如果 hashCode 值不相同,那 object”一定”不相同。
陣列:


一維陣列宣告:

int a1[] = new int[5];

int[] a1; a1 = new int[5]; // 但不可以 int[5] a1((宣告陣列大小只能在”=”右邊)

int testArray[]; testArray = new int[6]{1, 2, 3, 4 ,5 ,6};
多維陣列宣告:
int[][] a1 = {{1,2},{3,4,5},{6,7,8,9}};

宣告

// []內不可有 size
需特別注意的宣告:

String [] s1 = new String[]{“a”,”b”,”c”}; String [] s1 = new String[]{‘a’,’b’,’c’};

char [] c1 = new char[]{'a','b','c'}; char [] c1 = new char[]{“a”,”b”,”c”};

陣列宣告為 char 時,{}中可為 ‘a’ (~z)、’0’(~9)、0(~65535)、’\u0000’(~’\uFFFF’)

陣列宣告時若為{‘3’,’a’},無論型態為何,print 出來皆為 ANSI 碼,但需注意合法性(如上) 。

陣列宣告為 char 時若未給初值,則初值為”空白”,{‘ ’}是合法的,但{‘’}為不合法的,至
少要有空白(但若為 String,則””與” ”皆為合法的)。

宣告時就必須指定資料型態,且同一陣列中的元素其資料型態必須相同。

陣列宣告時,[]必須位於 type 或名稱的後面。
(int[] a1[],a2[] ; int []a5,a6[] ; int[] a7,a8[] ; int []a3,[]a4;)
可以

所有的陣列型態都是 implement 自” Cloneable interface”、” Serializable interface”,所
以任何一種 Array 都可被 assign 到 Cloneable type。
不可以
注意

Primitive array types 不可被相互 assigned (Long args = Integer args) 。

宣告大小與給予初始值不可同時出現,否則會 compile-time error,但也不可以兩者都沒有。

變數不可 assign 給二維陣列,一維陣列也不可 assign 給二維陣列。

陣列無論是否為 class-level 或 local 都一定會做 init,內容值則視 type 決定。

陣列的大小是 myAry.length,不是 myAry.length()。length 不須宣告,也不可更改。
-7
陣列的 index 只限於 byte、short、int、char 四種 type。

存取範圍超過 array 索引範圍會產生 Exception,為 runtime exception 不是 compile exception

byte [] ary1, ary2[]; //ary2 是二維陣列,小心不要上當。

float ary = new float [123]; //不合法,少括號; Object ary = new float[123]; // 合法
Garbage Collection:
讓物件能”有機會”被 garbage collected 的方法:


nulling a reference

reassigning a reference value

isolating a reference

gc runs in low memory situations。VM 將此 thread 的 priority 設為 0(最低)。

當系統有其它 thread 在運作時,就不會進行 GC。

只有 gc 可以 destroy 一個 object。

Runtime.getRuntime().gc()

finaliaze 被呼叫的時機為真正做 gc 之前。

The finalize method of each instance can only run once

String s = “Hello”; String s = nothing;
/
System.gc()
 is not garbage collected
String s = new String(“Hello”); String s = nothing;  is garbage collected
流程控制:
語法
注意事項
if (exp) { }

exp 須為 boolean type。(a==b 可以,但 a=b 不行,要注意)
else { }

else 可有可無,若無明顯{}分開,則是跟著上一個離自己最近的 if。
switch (exp) {

exp 須為 byte、short、char、int 其中一種 type。
case lable1 : statement1

case lable 只能是 static final 的變數。
default : default statement

case 與 case 間若無 break,則會 fall through 至下一個 case。

deralut 可有可無。

不可以兩個 case 放在同一行(case 1,2 : statement1)
while (condition) { }

condition 須為 boolean type。
do {

condition 須為 boolean type。
} while (condition);

至少會執行一次。

注意不要遺忘 while 之後的分號。

init 可以是 0 或 1 個以上的 exp,以逗號分隔。若是在 init 中宣告 var,
}
for (init ; boolean ; increasing)
則只能夠有一個 exp (int i=0,j=0;//算一個)。但 type 必須相同。
{
statement
}

boolean 可以是 0 或 1 個 boolean exp,若是空的表示 forever true。

increasing 可以是 0 或 1 個以上的 exp,以逗號分隔。

init、boolean、increasing 都可以省略,但是兩個分號不可省略。

for(a,b,c){d}執行時為 abdcbdc…,a 只有在一開始執行一次而已。

break 用於 while、do、for、switch。用以跳出。

continue 只能用於 while、do、for,不可於 switch。用以停止目前輪迴,開始下一輪迴。

label 可與 break、continue 合用,且 label 需以冒號”:”來結束(不是分號)。
Constructor:
執行
順序

配置參考變數,配置記憶體

預設初始化(將該 object 內所有 fields 全歸零)

明顯初始化(依定義順序執行 instance var init 及 instance(non-static free floating block) init,
-8此動作將與下個動作交叉執行)

執行連緒的建構子

當程式一直往上呼叫,在回程且跨越 class 時(從 Object 回到 A class),會先 check class A
是否有做明顯初始化。
語法
可以
不可以

constructor 第一行必須是 this(..)或 super(..),否則 JVM 會自己在第一行插入 super()。

this(...)是用來呼叫另一個 overloading constructor。使用時必須是 constructor 的第一行。

super(...)是用來呼叫父類別的某個 constructor,使用時必須是 constructor 的第一行。

方法名稱(Method)可以跟 Constructor 和 Class 名稱相同。

Constructor 可以用 public、private、protected、(default)修飾。

使用 private 的影響為避免被實體化(instantiates)。

可以 overloading constructors 來定義一個以上的 constructors。

constructor 可以丟出 Exception。

constructor 不能有回傳值、也不能夠被繼承。

不能 overriding constructors。

constructor 內不可以同時有 this(...)或 super(...)。

constructor 不會被繼承,如果自己沒有寫 constructor,compiler 時會加入 default constructor ,
為一個 no parameters and throws no exceptions,其存取權限將與 class 相同。特別注意,若
已定義 constructor 後,compiler 就不會再給 default constructor。
注意

在繼承的情況下,如果 superclass 的 constructor 有定義 Exception in the throws clause,那麼
他的 subclass 也必須定義 Exception in the throws clause。
overloading 與 overriding

overloading 與 overriding 的觀念:
名字一樣,給不同的條件(參數,多寡或順序不同即可)做不同的事。譬如上班(){},帶參數”SR”
overloading
時是在執行”趕工寫程式”,不帶參數時是在執行”摸魚”。注意,回傳值不同不可代表 overload,
且會造成 compiler error。
名字一樣,且條件(參數及回傳值)也要一模一樣。主要是覆寫掉繼承來的東西。譬如繼承了超
overriding
認真的做人態度,就一定會變得超認真(預設繼承來是不能選擇的)只要可以做到接觸的比爸媽
更多(access modifier 要更大)且犯更少的錯(throws exceptions 範圍要更小),就懂得用另
一種態度來生活。

overloading 與 overriding 的區別:
Access
Return
Method
modifier
type
name
dont’ care
dont’ care
同
不小
同
同
meaning
overloading
overriding

reuse the
method name
redefine the
method
Para list
不同(type,
count,order)
同
Throws
exceptions
dont’ care
subset
overriding 需特別注意是否滿足下列條件,否則會 compiler error。

access modifier--不小:


ruturn type、para list--同


subclass 的 access modifier 不可比 superclass 的 access modifier 小。
subclass 與 superclass 的 return type 與 para list 須相同。
throws exceptions—subset

subclass 所丟出的 checked exception 範圍不可超過 superclass 所丟出的 exception。
-9
final methods 不可被 overridden。

final class 中的所有 methods 不會被 overridden,因為 final class 不會有 subclass。

private method 不會 overridden,因為 subclass 不會繼承 superclass 的 private members。

overriding method(subclass)不可以是 static method。

static method 不可被 non-static method overridden,只可被 subclass 的 static method shadowed

override superclass 時只有 method 會被覆寫,property 不會被覆寫。
Inner Classes(內部類別)
定義在 class 中的 class 即稱為 inner class。
觀念
Static Member Class
Member Class
分類
(匿名 Class)


類似 containing class 的 static member,與 containing class 的
instance 沒有關聯。

類似 containing class 的 instance field 或 instance method。每個
member class 的 instance 是與 outer class 的 instane 結合在一起的。

有效範圍只限於這個區塊內。

local var 的生命,始於 java interpreter 進入它所在的 block 執行,結
束於 java interpreter 離開它所在的 block。
Local Class
Anonymous Class
識別法


local class 的 instance 的生命比 local var 還長(見範例)。

若一個 class 只會在某個 method 內被使用,可使用 local class。

是 local class 的一種,但沒有 class name。

不能有 consturctor(可用 instance init 代替)。

若某 class 只會被使用一次,可使用 anonymous class。
在 class 內的 class

public static class Inner{ }  Static Member Class

public class Inner{ }  Meber Class
在 class 內的 method 內的 class

class Inner{ }  Local Class

new ClassName(para) { }
/ new InterfaceName() { }  Anonymous Class
Access modifiers
修飾字
Static Member Class
可宣告為 public、protected、default、private
Meber Class
可宣告為 public、protected、default、private
Local Class
不可宣告為 public、protected、default、private
Anonymous Class
none
static members
instance member
yes
No
Inner
Static Member Class
可存取
Meber Class
Yes(包含繼承來的)
之範圍
Local Class
Yes(區塊內的”final” local var 也可以)
Anonymous Class
None
可宣告
成員
static members
instance member
Static Member Class
yes
Yes
Meber Class
No(但可宣告常數 static final)
yes
Local Class
No(但可宣告常數 static final)
Yes
Anonymous Class
使用
Static Member Class
none
Outer.Inner in = new Outer.Inner() ;
-10方式
Meber Class
Outer.Inner in = new Outer().new Inner() ;
Local Class
(見範例)
Anonymous Class
可以

new ClassName ([paralist]) {class body}

new InterfaceName () {class body}

inner class 內的程式碼可像 outer class 的 method 般直接存取 outer class 的 fields 及 methods。

在 containing class 中,可直接使用 inner class 的 class name,但在 containing class 外,須使
用 inner class 的 qualified name—OuterClassName.InnerClassName。
不可以
範例

inner class 的命名不可與它的 outer class 或 package 的命名相同。(但 field 與 method 的命名可)
Static Member
Class
1. public class Test {
2.
static private int i = 0;
3.
static private void 印出 i() { System.out.print(i); }
4.
protected static class Inner {
5.
private void g() {
6.
i = 2;
7.
印出 i();
8.
}
9.
public void h() {
10.
i = 3;
11.
印出 i();
12.
}
13.
public static void main(String[] args) {
14.
Inner inn = new Inner();
15.
inn.g(); //2
16.
}
17.
}
18.
public static void main(String[] args) {
19.
Inner inn = new Inner();
20.
inn.g(); //2
21.
}
22.}
23. class A {
24.
public static void main(String[] args) {
25.
Test.Inner ic = new Test.Inner();
26.
ic.h(); // 3
27.
}
28. }
-11-
Meber Class
Local Class
1. class InnerSuper { protected int i = 1; }
2. class OuterSuper { protected int i = 2; }
3. public class Test extends OuterSuper {
4.
private int i = 3;
5.
public class Inner extends InnerSuper {
6.
private int i = 4;
7.
public void f() {
8.
int i = 5;
9.
System.out.print(i);
// 5
10.
System.out.print(this.i);
// 4
11.
System.out.print(super.i);
// 1
12.
System.out.print(Test.this.i); // 3
13.
System.out.print(Test.super.i); // 2
14.
}
15.
}
16.
public static void main(String[] args) {
17.
Test t = new Test();
18.
Inner inn = t.new Inner();
19.
inn.f();
20.
}
21.}
22. class A {
23.
public static void main(String[] args) {
24.
Test.Inner inn = new Test().new Inner();
25.
inn.f();
26.
}
27.}
1. class InnerSuper { protected int x = 1; }
2. class OuterSuper { protected int y = 2; }
3. interface ForPolymor { void f(); }
4. class Test extends OuterSuper {
5.
private int z = 3;
6.
public ForPolymorphism g() {
7.
final int i = 4;
8.
int j = 5;
9.
class Inner extends InnerSuper implements ForPolymor {
10.
int k = 6;
11.
public void f() {
12.
int m = 7;
13.
System.out.print(x);
// 1
14.
System.out.print(y);
// 2
15.
System.out.print(z);
// 3
16.
System.out.print(i);
// 4
17.
//System.out.print(j); // compile error
18.
System.out.print(k); // 6
19.
System.out.print(m); // 7
20.
}
21.
}
22.
Inner in = new Inner(); //create Inner class 的 object
23.
in.f(); //呼叫 Inner class 的 method
24.
return in;
25.
}
26.
public static void main(String[] args) {
27.
Test t = new Test();
28.
//Inner in = new Inner(); in.f(); //Inner is out of scope
29.
ForPolymor fp = t.g();
30.
fp.f();
31.
}
32.}
-12-
Anonymous Class
(匿名 Class)
1. class A {
2.
int i;
3.
A(int i) { this.i = i; }
4.
void f() {System.out.println("A");}
5. }
6. class Test {
7.
public void g(A a) { a.f(); }
8.
public static void main(String[] args) {
9.
Test t = new Test();
10.
t.g(
11.
new A(2) {
12.
void f() {System.out.println(i);}
13.
}
14.
); // 2
15.
}
16.}
Exception:
目的

當發生錯誤或執行到一個 throw statement,馬上停止正常的程式執行,去尋找適當的 exception
handler 來處理 throw statement 所丟出的意外狀況。

可以用在 throw statement 的:Error、Throwable、Exception、RuntimeException

所有的 exception 都是 java.lang.Throwable 的 subclasses,可分為三大類:
名稱(with subclasses)
需 catch
發生原因
嚴重的狀況如 out of memory 幾乎不可能收拾。程式中
分類
java.lang.Error
no
任何補救,所以很少人會去 catch 這類的 exception。
java.lang.RuntimeExeption
no
java.lang.Exeption(java.lang.
yes
RuntimeExeption 除外)

declaring
方式

program bug,如 int i = 3/0;會發生
java.lang.ArithmeticException。
環境問題,如程式要讀取某網頁但該網站當機等。無法防
止這類狀況發生,只能 catch 這個 exception。
需 catch 的 exception 處理方式:
handling
處理
可以 catch 這類的 exceptions,但 catch 到後也不能做
使用 try-catch-finally statement 自己處理。
使用 throws 子句,宣告自己可能會丟出某些 exception,而將 exceptions 丟給 caller 處
理。Caller 自己就不須用 try-catch-finally block 來處理。
exception 發生時處理方式:
找到適當
執行 catch block,再執行 finally block,然後程式執行恢復正常。(即執行 finally block
catch block
之後的 statement)
未找到適當
執行 finally block,再將控制權交給外層的 try/catch/finally statement。若所有外層
catch block
都未 catch 住這個 exception,程式異常終止。

try / catch / finally 順序不可顛倒。try 之後可以只跟 catch 或只跟 finally,但不可無 catch 也無 finally。

catch block 的順序規則:

執行
順序
particular exception block 須定義在前,general exception 須定義在後。(catch 時 Exception
在前,Throwable 在後)

若前面已 catch 某 class 的 exception object,後面的 catch block 不可再宣告 catch 該 class
或該 class 的 subclass。

注意
定義在 finally block 中的程式一定(must)會被執行,即使 exception 發生但沒有 catch block 或是在
try 或 catch 的 block 中寫 return,還是會被執行,除非在 try 或 catch 的 block 中執行到 System.exit()
或是在 finally block 中發生了 exception。
-13
finally block 的動作會蓋過前面 try 或 catch block 的動作。即 finally block 的 return 或 throw
statement 會蓋掉 try 或 catch block 的 return 或 throw statement。

一個 overriding method 所丟出的 exceptions 不能超過 overridden method 所丟出的 exceptions
範圍,否則會發生 compiler error。(即子類別的 exception 可以與父類別 exception 相同或為該
exception 的 subclass,但不可大於父類別的 exception)
Assertions:
意義
注意

驗證一個 class 的 method 是否被正確的呼叫。

進階的 exception handling,只可丟出 AsserttionError。

assert statement 如果放在”unreachable”的地方,compiler 時會產生 error。

預設 compiler time 與 run time 是不支援 assertion statement。

程式中如果有使用 assert,在 complier 時就一定要加上-source 1.4 的選項,否則會 compiler error。
expression1 需為 boolean type,否則會 compile error。意
assert expression1;
思為當程式執行到此,expression1 的結果一定為真,若為假則
丟出一個沒有任何 error msg 的 AsserttionError。
宣告
方式
assert expression1 : expression2;
expression1 需為 boolean type,且 expression2 的求值結
果不可為 void,否則會 compile error。意思為若 exp1 的結果
為假,則丟出由 exp2 所提供的 error msg 的 AsserttionError。

run time 時要 enable 或 disable assertion checking 時:
要 enable 時
system classes
使用
方式
-esa / -enablesystemassertions
non-system classes

要 disable 時
-ea / -enableassertions
-da / -disableassertions
Assertions can be selectively enabled for...
named class
won’t automatically enabled for any subclass of the named class
named package
will automatically enabled for the subpackages
unnamed package
in the current working directory
won’t enabled if in any named directory
檢定 private methods 的 precondition,確保在進行某些操作前已滿足先決條件。(輸入的月份需
>=1 且<=12 才進行該月有幾天的計算)
檢定所有 methods 的 postcondition,確保某些操作後,即定條件仍滿足。(計算的天數結果需>=28
適
合
使
用
且<=31 才將天數 ruturn 回去)
檢定 class invariant。確保在任何情況下,某個不變的狀態必須滿足。class invariant 必須在這個
使用
class 的每個 public methods 及 constructors 結束之前做才可確保不變狀態。
時機
在 switch case statement 中如果需在每個 case 做 return,則在 default 使用”throw new
AssertionError()”比使用 assert statement 更來得恰當(因無論有無加-source 1.4 都不會 error)
public methods 的 arguments checking,因為 argument checking 是永遠要做的,而 assertions
不
要
使
用
卻不一定永遠會被執行。
Assertion statements 不可有任何副作用。因為 assertion 可能被 disabled,所以不要用 assertion
statement 去改變 instance var 的值或影響 method 的 ruturn value。
Polymorphism
-141.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
class A{
int x = 1;
int y = 2;
int f() { return x; }
static char sf() { return ‘A’; }
}
class B extend A{
int x = 3; // shadowing
int z = 4;
int f() { return x; } // overriding
static char sf() { return ‘B’;} //shadowing
int g(){ int x = 1; return (x+this.x); }
}
class Z extend A{ }
15. public class SCJP {
16. pubilc static void main(String[]
17.
A a = new B();
18.
B b = new B();
19.
B bb = new Z();
20.
System.out.println(a.f());
21.
System.out.println(a.g());
22.
System.out.println(a.z);
23.
System.out.println(a.x);
24.
System.out.println(a.y);
25.
System.out.println(a.sf());
26.
System.out.println(b.x);
27.
System.out.println(b.sf());
28. } }
args){
//error
// 3
// error
// error
// 1
// 2
// ‘A’
// 3
// ‘B’
● 意思是 superclass 的 reference var 可以 refer to 所有 subclass 的 instance。(指的是
reference variable 不是 object,只要是 subtype 就可以)
Assignment
● 如第 17 行。第 19 行會產生 compile error,因 class Z 不是 class B 的 subclass
● virtual mehhod invocation,建立在 method overriding 及 polymorphic assignment 上。
Method
Invocation
● 如第 20 行。第 17 行宣告一個 class A 的 reference var “a”並 refer to subclass B。
Compile-time
● compile-time type 是 reference var 的 type,run-time type 是 object 的 type。
and Run-time
● 第 17 行,compile-time 時 a 是 A type,runt-time 時 a 是 B type。
● 第 21 行 compile err 因為此時 a 為 A type,需轉型為 ((B)a).g() 才可以被執行。
Type
● instance method 只能被 overridden,而 class method 及 field 只能被 shadowed。
Overriding
● overriding instance method 才有所謂的 compile time type 及 run time type。
● shadowing class method / field 永遠只有一種 type,就是 reference var 的 type。
and
Shadowing
● 第 23 行 x 和第 25 行 sf()是 shadowing。要看 reference var 的 type (A)。
● 第 27 行最好改為標準呼叫方式 B.sf()。
Interface
1. class YourClass{ }
2. interface YourInterface
3. {
4.
void a();
5.
//static final void b();
6.
public static final int var = 1;
7. }
8. public class MyInterfaceClass extends
YourClass implements YourInterface
9. {
10.
interface Interface1{ }
11. public void a(){}
可以
12.
13.
14.
15.
16.
17.
18.
19.
20.
21. }
public abstract interface MyInterface
extends Interface1
{
public void f();
//MyInterface(){}
}
public static void main(String args[])
{
//new MyInterface();
}

Line 12:interface 可以繼承多個 super-interface。

Line 2、10、12:interface 可使用的 modifiers 只有 public 及 abstract。

Line 6:可以在 interface 內宣告 fields,但這些 fields 必須是"public static final"(常數
constant)。"public static final"可以省略,但不可以是 blank final,即一定得設定初始值,因此
interface 內不可能會定義任何的 instance variable。

不可以
注意
Line 4、5:不可以在 interface 內宣告 protected、private、static 或 final method,且 interface
內的 method 不可有 method body({})。否則會 compiler error。

Line 15:interface 內不可定義任何的 constructor。

Line 19:interface 及 abstract class 不可被被實體化,因尚未定義完整(內含 abstract method)。
class

Line 11:若一個 class implements 某個 interface,這個 class 就必須實做
-15(implement)這個 interface 內所定義的所有 abstract methods(即長出 method
body{}來),否則這個 class 必須宣告為 abstract class。
Line 8:一個 class 只能 extends 一個 superclass,但可以 implements 一個以上

的 interface,而且 implements 子句不可出現在 extends 子句之前。class 會去
implements interface 主要目地是為了多型(polymorphism)。
Line 4、5:在 interface 內的 method 不管是否有加 public abstract,一定都是

method
public abstract method。
Wrapper Classes(包裝類別)



特別注意常出現狀況

Wrapped values 不能被更改。

不能直接把 Boolean 拿來 evaluate true/false 值,否則會 compiler error。

不同 class 的 wrapper class,即使值相同,用 equals()去比也是 false。

primitve xxxValue()

primitive parseXXX(String) //只接受 String 引數,回傳 primitive

Wrapper valueOf(String) //只接受 String 引數,回傳 wrapper object
//不接受任何引數,回傳 primitive
primitive data types / wrapper classes
primitive types
Wrapper classes
boolean
Boolean
byte
Byte
short
Short
int
Integer
long
Long
char
Character
float
Float
double
Double
用 Primitives 產生 String / 從 String 中剖析出 Primitives
primitive value 轉成
string object 剖析成
string object
primitive values
直接將 primitive value 轉成 string object
直接將 string object 剖析成 primitive values
classes
意義
注意事項
舉例

為 static method

為 static method

radix 可是任意基底

radix 可是任意基底

會 throws NumberFormatException

return type 是 primitive type
Integer.toBinaryString(15)
//1111
Integer.parseInt(“15”)
//15
Integer.toOctalString(15)
//17
Integer.parseInt(“15”,16)
//21
Integer.toHexString(15)
//f
Integer.parseInt(“f”,16)
//15
Integer.toString(15,3)
//120
Integer.parseInt(“1010”,2) //10
Integer.parseInt(“0xf”,16) //丟出
NumberFormatException
Byte
Short
String toString(type s)
ex : String toString(byte s)
//type 為對應之 primite type(byte、
short、boolean、char、float、double)
long parseByte(String s)
long parseByte(String s,int radix)
long parseShort(String s)
long parseShort(String s,int radix)
-16Float
float parseFloat(String s)
Double
double parseDouble(String s)
Boolean
Character
Integer
Long
String toBinaryString(type i)
int parseInt(String s)
String toHexString(type i)
int parseInt(String s,int radix)
String toOctalString(type i)
long parseLong(String s)
String toString (type i)
long parseLong(String s,int radix)
String toString(type i,int radix)
// type 為對應之 primite type(int、long)

由 Primitive 產生 Wrapped objects / 取出 Wrapped Objects 內的 Wrapped Value
由 Primitive 產生
取出 Wrapped Objects 內的
Wrapped objects
Wrapped Value
將 primitive value 包裝成 wrapped object
取出 wrapped objects 內的 wrapped value
classes
意義

注意事項
Integer wi = new Integer(15);
Integer wi = new Integer(15);
Boolean wb = new Boolean(true);
println(wi.doubleValue()); //15.0
Type(type val)
boolean booleanValue()
ex : Boolean(boolean val)
char charValue()
// Type 為對應之 Wrapped Object
byte byteValue()
(Boolean、Character、...)
short shortValue()
Long
// type 為對應之 primite type
ing intValue()
Byte
(boolean、char、...)
long longValue()
舉例
Boolean
Character
Short
Integer
float floatValue()
Float
double doubleValue()
Double

為 instance method
從 String 產生 Wrapped Object
classes
意義
注意事項
method
將對應的 primitive value 包裝成 wrapped object。

為 constructors 或 static methods。

static methods 的 return type 是 wrapper class 而非 primitive type。

都會 throws NumberFormatException。

若 string 的開頭是”0X”、”0x”、”#”,則以 16 為基底來 parse(開頭 0 以 8 為基底),
否則以 10 為基底來 parse。

舉例
radix 可是任意基底。
valueOf(String s)
以 10 為基底來 parse string ”s”。
decode(String s)
先看”s”字串的開頭為何再決定以 16、10 或 8 為基底來 parse。
Integer.decode(“15”).byteValue()
//15
Integer.decode(“030”).shortValue()
//24
Integer.decode(“0x0f”).intValue()
//15
Integer.valueOf(“100”).byteValue()
//100
Integer.valueOf(“2w”).byteValue()
//throws NumberFormatException
Integer.valueOf(“f”,16).byteValue()
//15
-17Integer.valueOf(“20”,3).byteValue() //6
Character
Boolean
Float
Double
Short
// constructor
static Type valueOf(String)
// Type 為對應之 Wrapped Object(Boolean、Float、Double)
Type(String s)
// constructor
Integer
static Type decode(String s)
Long
static Type valueOf(String s)
Byte

Type(String s)
static Type valueOf(String s,int radix)
// Type 為對應之 Wrapped Object(Short、Integer、Long、Byte)
Character 內常用的 Class Methods
用途
改變或判斷 char value
Character.isLetter(‘a’); // true
舉例
Character.isDigit(‘5’); // true
Character.toLowerCase(‘Q’); // q
static boolean isDigit(char ch)
static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
methods
static boolean isLowerCase(char ch)
static boolean isUpperCase(char ch)
static boolean isWhiteSpace(char ch)
static char toLowerCase(char ch)
static char toUpperCase(char ch)
Utility Classes

class、method、constructor、Boolean、...都是 object。

System Properties(系統參數)
用途
取出或設定系統參數
java –Deigh=8 Test
println(System.getProperty(“java.version”));
//1.4.2
System.setProperty(“two”,2);
Integer wi = Integer.getInteger(“two”);
舉例
println(wi.toString);
//2
System.setProperty(“love”,”true”);
boolean b = Boolean.getBoolean(“love”);
//true
Ingeger wi2 = Integer.getInteger(“eigh”,999);
println(wi2.toString());
//若最上面那行有加-D 的話為”8”,否則為”999”
static Integer getInteger(String key)
Integer
static Integer getInteger(String key, int val)
static Integer getInteger(String key, Ingeter val)
methods
static Long getLong(String key)
Long
static Long getLong(String key, int val)
static Long getLong(String key, Long val)
Boolean
static boolean getBoolean(String key)
-18參數”key”指的是 propery name,”val”是 defalut value,若 system.propery 內
注意
(java.version、java.home....)沒有定義所指定的 key,則 return ”val”。
新增系統參數
用 System 所定義的 class method
System.setProperty(“abc”,”33”);
啟動 java interpreter 時使用-D option
java –Dabc=88 Test

System 所定義的
class method
String val = System.getProperty(“abc”);
取 key 為”abc”的系統參數,若沒定義”abc”則傳回”null”。


String val = System.getProperty(“abc”,”33”);
取 key 為”abc”的系統參數,若沒定義”abc”則傳回”33”。

取得系統參數

Integer、Long 及
Integer wi = getInteger(“abc”);
取 key 為”abc”的系統參數,若沒定義”abc”或 numeric

Boolean 所定義的
class methods
format 不合,則傳回 null。

Ingeger wi = getInteger(“abc”,33);
取 key 為”abc”的系統參數,若沒定義”abc”則傳回”33”。


The Math Class
注意
舉例

是一個 final class,故不可被繼承,且所有的 mebers 都是 static members。

只有 private constructor,故無法 create 一個 Math object(也不須 create Math object)

不會 throws 任何的 exception。

對負數做開根號 sqrt()所得結果為 NaN。

Long、Ingeger 的最小絕對值是負的。

sin 45 度角的值計算方式:(r 即為最後的值)

double d = Math.toRadians(45.5); double r = Math.sin(d);
(int、float、long、double)
簡單的記
double random()、
奇怪的
long round(double a)、int round(float a)
只有 double
constants

abs、max、min
static final double E
剩下的其他 method
// e(2.718) ; static final double PI // π(3.141)
double sin(double a) // sign of a
三角函數
double cos(double a) // cosign of a
double tan(double a)// tangent of a
//”a”是 angle(角度)單位為 radians(弧度)
角度 / 弧度
double toRadians(double deg) // 單位為 degrees(度數)
double toDegrees(double rad) // 單位為 radians(弧度)
double exp(double a) // ea
methods
次方
double pow(double a,double b) // ab
double sqrt(double a) // a 開根號
亂數
最大/最小 整數
double random()//大於 0.0 但小於 1.0 的隨機數值
double ceil(double a) // >= ”a”的最小整數(無條件進入)
double floor(double a) //<= ”a”的最大整數(無條件捨去)
double rint(double a)
最接近”a”的整數
int round(float a)
long round(double a)
絕對值
int abs(int a)
-19long abs(long a)
float abs(float a)
double abs(double a)
int max(int a, int b)
較大值
long max(long a, long b)
float max(float a, float b)
double max(double a, double b)
int min(int a, int b)
較小值
long min(long a, long b)
float min(float a, float b)
double min(double a, double b)

String and StringBuffer Classes

String object 是不可變的,產生之後”值”就不可被改變,大部份的 method 都是 return
一個新的 string object,所以 String class 內不會有 setXxxx() method。

空值不能呼叫 concat(),否則會 runtime error。
產生字串
字串長度

toString()

static String valueOf(type a)//type 為各個 primite type
instance method — int length()

取出字串
String substring(ing begIndex)
//”abcdef”.substring(1)bcdef

String substring(int begIndex,int endIndex)
//”abcdef”.substring(1,3)bcde
串接字串

String concat(String str)//附加在原 string 的後面

char charAt(int index)
//char ch = “abcd”.charAt(2)傳回’c’
取出字元

void getChars(int srcBegin,int srcEnd,char[] dst,int dstBeg)
//char[] ca=new char[5] ; abcdef.getChars(1,4,ca,1);
ca 內容為{‘\u0000’,’b’,’c’,’d’,’\u0000’}
String
比較字串

char[] toCharArray() //把 String 轉換為 char array

boolean equals(Object anObject)

boolean equalsIgnoreCase(String anotherString)

boolean startsWith(String prefix)

boolean startsWith(String prefix,int offset)

boolean endsWith(String suffix)

int compareToIgnoreCase(String str)

int compareTo(String argStr)
//int i = str.compareTo(argStr)0 為 str 與 argStr 相同
尋找字串

int indexOf(int ch);int indexOf(int ch, int fromIndex)

int lastIndexOf(int ch);int lastIndexOf(int ch, int fromIndex)

int indexOf(String str);int indexOf(String str,int fromIndex)

int lastIndexOf(String a);int lastIndexOf(String a,int frIndex)
// return -1 代表沒找到
取代字元

String replace(char oldChar, char newChar)
-20// “abbbcdeb”.replace(‘b’,’k’)”akkkcdek”
Trim
intern
String trim()

//移除 string 前後兩端的”white space”(如空白或’\t’...)
intern()

//將 string 加入 string pool(若 pool 尚無相同 content 的 string object)

StringBuffer 是可變的。

StringBuffer 沒有 override equals()

StringBuffer append(Object obj)

StringBuffer append(String str)

StringBuffer append(char[] str)

StringBuffer append(char[] str, int offset, int len)

StringBuffer append(boolean b);StringBuffer append(char c)

StringBuffer append(int i);StringBuffer append(long l)

StringBuffer append(float f);StringBuffer append(double d)

StringBuffer insert(int index, char[] str, int offset, int len)

StringBuffer insert(int offset, Object obj)

StringBuffer insert(int offset, String str)

StringBuffer insert(int offset, char[] str)

StringBuffer insert(int offset, boolean b)

StringBuffer insert(int offset, char c)

StringBuffer insert(int offset, int i)

StringBuffer insert(int offset, long l)

StringBuffer insert(int offset, float f)

StringBuffer insert(int offset, double d)

StringBuffer delete(int start, int end)

StringBuffer deleteCharAt(int index)
取代字串

StringBuffer replace(int start, int end, String str)
顛倒字串

StringBuffer reverse()
續接字串
StringBuffer
插入字串
刪除字串
Threads(執行緒)
注意

main() method 本身就是一個 thread。

程式進入 main()之後,就有兩個 thread 了,main()與 garbage collection。

一個 thread 是一個 object,要產生一個 thread 必須透過 java.lang.Thread 這個 class。

run() method 的語法為”public void run() { ... }”。

wait(); notify();及 notifyAll();須在 synchronized context 下使用,不然會產生 runtime
exception:IllegalMonitorStateException。

sleep()會丟出 InterruptedException,使用需有 try…catch,不然就要 declare throws
InterruptedException。

重覆呼叫同一執行緒的 start(),會導致 IllegalThreadStateException,為 runtime exception

synchronized 不可用在 constroctor。
-2101
02
03
04
05
06
07
08
09
10
11
implementing
Runnable interface

class MyThread implements Runnable {
public void run() { /*....*/ }
}
public class Test {
public static void main(String args[]) {
MyThread r = new MyThread();
Thread t = new Thread(r);
t.start();
//......
}
}
定義一個 implement Runnable interface 的 class,且一定要
implements run() method,並 instantiates 這個 class,並將
此 class 的 instance 傳給 Thread()。
產生
執行緒

Line 7:”r”必須是 an instance of Runnable,否則會 compile error。

Line 7:thread “t”被建立後不會馬上執行,必須呼叫 start()後才執行。
01 public class MyThread extends Thread {
02
public void run() { /*......*/ }
03
public static void main(String[] args) {
04
MyThread t = new MyThread();
05
t.start();
06
}
07 }
extends Thread

定義一個”java.lang.Thread”的 subclass,overrides run() method,
然後 instantiates 這個 subclass。


Line 1:要 extends Thread class

Line 2:要 override run() method,否則會是空的。

Line 4:要 instantiates Thread 的 subclass。
thread 被 new 出來後不會馬上執行 run()method,必須執行 start()後才會進入
runnable 狀態。
注意

thread 在 running state 時所執行的是這個 thread 的 run()method。

thread 從 runnable 到 running(實際在 CPU 執行)或反之是由 JVM 的 thread
scheduler 任意決定。
控制
執行緒
不可以

不管呼叫什麼,頂多只能讓狀態變成 runnable,不可能馬上變成 running。

一個 thread 的 run()method 結束時,這個 thread 就進入 dead state(死掉了),不
可以再 restart 一個 dead thread(即再呼叫 start()method),否則會 compile error。

狀態
改變
thread 遇到下列狀況時,會從 running 換到 blocked state

Input/Ouput blocked

sleep()、join()、wait()

進入 synchronized block,但此 synchronized block 所保護的 object lock 已
經被其他 thread 取走。
method
Features
yield()
method
run()
Method Type
static
instance
Class
Thread
Thread
start()
instance
Thread
interrupt()
instance
Thread
-22會丟出 InterruptException
sleep(ms)
static
Thread
instance
Thread
instance
Object
ms 是 long type,單位是 millisecond
ms 不可省略
會丟出 InterruptException
join(ms)
ms 是 long type,單位是 millisecond
若 ms 為 0 或空值,則表等待的時間為永遠
會丟出 InterruptException
wait(ms)
ms 是 long type,單位是 millisecond
若 ms 為 0 或空值,則表等待的時間為永遠
須事先拿到 this object 的 lock
notify()
須事先拿到 this object 的 lock
instance
Object
notifyall()
須事先拿到 this object 的 lock
instance
Object
-23-
The Collection Framework

繼承圖
<<interface>>
Collection
Vector
<<interface>>
<<interface>>
List
Set
ArrayList
LinkedList
HashSet
<<interface>>
SortedSet
LinkedHashSet
Stack
<<interface>>
Map
Hashtable
HashMap
<<interface>>
SortedMap
Properties

LinkedHashMap
TreeMap
特性表
有順序
可重覆
Vector
List
Yes
LinkedList
No
No
ArrayList
Set
LinkedHashSet
TreeSet
No
Yes
No
Map
LinkedHashMap
TreeMap
No
No
Yes
No
Yes
No
HashMap
No
Yes
Hashtable
Properties
排序
Yes
Stack
HashSet
Thread safe
No
Yes
TreeSet
Related documents