一些常用的JSF TAG使用範例和效果.
http://dream.mods.jp/first_jsf/part5.html
http://www.jsftoolbox.com/documentation/help/12-TagReference/index.jsf
2009年4月20日 星期一
2009年3月2日 星期一
Thread Safe Collections
Thread Safe Collections //ref from: http://en.wikibooks.org/wiki/Java:Collections
It is also called Concurrent Collections. Most of the popular collection classes have implementations for both single thread and multiple thread environments. The non-syncronized implementations are always faster. You can use the non-syncronized implementations in multiple thread environments, when you make sure that only one thread updating the collection an any given time.
A new Java JDK package was introduced at Java 1.5, that is java.util.concurrent. This package supplies a few Collection implementations designed for use in multithreaded environments.
The following table list all the syncronized collection classes
It is also called Concurrent Collections. Most of the popular collection classes have implementations for both single thread and multiple thread environments. The non-syncronized implementations are always faster. You can use the non-syncronized implementations in multiple thread environments, when you make sure that only one thread updating the collection an any given time.
A new Java JDK package was introduced at Java 1.5, that is java.util.concurrent. This package supplies a few Collection implementations designed for use in multithreaded environments.
The following table list all the syncronized collection classes
syncronized | non-syncronized | |
---|---|---|
List | java.util.Vector | java.util.ArrayList |
java.util.Stack | ||
java.util.LinkList | ||
java.util.concurrent.CopyOnWriteArrayList | ||
Set | java.util.TreeSet | |
java.util.HashSet | ||
java.util.LinkHashSet | ||
java.util.concurrent.CopyOnWriteArraySet | ||
Map | java.util.TreeMap | |
java.util.Hashtable java.util.concurrent.ConcurrentHashMap | java.util.HashMap | |
java.util.LinkHashMap | ||
java.util.IdentityHashMap | ||
java.util.EnumMap |
the default size of Vector, Arraylist, Hashtable, Hashmap, Hashset in Java
Vector - 10, Arraylist - 10, Hashtable - 11, Hashmap - 16, Hashset - 16
2009年2月26日 星期四
第234題
Given:
foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object.
The thread foo is currently executing bar.wait().
From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?
A. foo.notify();
B. bar.notify();
C. foo.notifyAll();
D. Thread.notify();
E. bar.notifyAll();
F. Object.notify();
答案:E
參考:13-5 執行緒的互動處理
------------------------------------------------------
foo and bar是二個物件,而foo 是一個Thread 的物件,而bar 為該bar Thread 要存取的物件
目前 thread foo正在執行bar.wait(),
另一條thread 如要喚醒的話,有何方式保證foo will stop executing wait()
bar.notifyAll();喚醒正在等待bar物作的所有thread
bar.notify();隨機喚醒正在等待bar物作的一條thread
foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object.
The thread foo is currently executing bar.wait().
From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?
A. foo.notify();
B. bar.notify();
C. foo.notifyAll();
D. Thread.notify();
E. bar.notifyAll();
F. Object.notify();
答案:E
參考:13-5 執行緒的互動處理
------------------------------------------------------
foo and bar是二個物件,而foo 是一個Thread 的物件,而bar 為該bar Thread 要存取的物件
目前 thread foo正在執行bar.wait(),
另一條thread 如要喚醒的話,有何方式保證foo will stop executing wait()
bar.notifyAll();喚醒正在等待bar物作的所有thread
bar.notify();隨機喚醒正在等待bar物作的一條thread
第235題
Given:
11. public class PingPong implements Runnable{
12. synchronized void hit(long n){
13. for(int i=1; i<3; color="#ffffff">CD
參考:13-4 執行緒的同步性與安全性
-----------------------------------------------
解析:雖然第12行的hit()方法加上synchronized ,但第17,18行各自啟動1條Thread
並在第21行透過不同的pingping物作呼叫第12行hit()方法,所以同一時間這2 條Thread
都可以執行,因為synchronized 無法鎖定不同物件的Thread;因此輸出時會看到2條Thread
(例如Thread id 分別為7和8)交互執行,並各自遞增i的值,而不會影響對方
11. public class PingPong implements Runnable{
12. synchronized void hit(long n){
13. for(int i=1; i<3; color="#ffffff">CD
參考:13-4 執行緒的同步性與安全性
-----------------------------------------------
解析:雖然第12行的hit()方法加上synchronized ,但第17,18行各自啟動1條Thread
並在第21行透過不同的pingping物作呼叫第12行hit()方法,所以同一時間這2 條Thread
都可以執行,因為synchronized 無法鎖定不同物件的Thread;因此輸出時會看到2條Thread
(例如Thread id 分別為7和8)交互執行,並各自遞增i的值,而不會影響對方
第233題
Given:
1. public class Threads1{
2. int x = 0;
3. public class Runner implements Runnable{
4. public void run(){
S. int current = 0;
6. for(int i=0; i<4; i++){
7. current = x;
8. System.out.print(current + ", ");
9. x = current + 2;
10. }
11. }
12. }
13.
14. public static void main(String[] args){
15. new Threads1().go();
16. }
17.
18. public void go(){
19. Runnable rl = new Runner();
20. new Thread(r1).start();
21. new Thread(r1).start();
22. }
23. }
Which two are possible results? (Choose two.)
A. 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
答案:AC
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
1. public class Threads1{
2. int x = 0;
3. public class Runner implements Runnable{
4. public void run(){
S. int current = 0;
6. for(int i=0; i<4; i++){
7. current = x;
8. System.out.print(current + ", ");
9. x = current + 2;
10. }
11. }
12. }
13.
14. public static void main(String[] args){
15. new Threads1().go();
16. }
17.
18. public void go(){
19. Runnable rl = new Runner();
20. new Thread(r1).start();
21. new Thread(r1).start();
22. }
23. }
Which two are possible results? (Choose two.)
A. 0, 2, 4, 4, 6, 8, 10, 6,
B. 0, 2, 4, 6, 8, 10, 2, 4,
C. 0, 2, 4, 6, 8, 10, 12, 14,
D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
答案:AC
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
第236題
Given:
1. class Computation extends Thread{
2.
3. private int num;
4. private boolean isComplete;
5. private int result;
6.
7. public Computation(int num){this.num = num;}
8.
9. public synchronized void run(){
10. result = num * 2;
11. isComplete = true;
12. notify();
13. }
14.
15. public synchronized int getResult(){
16. while(!isComplete){
17. try{
18. wait();
19. }catch(InterruptedException e){}
20. }
21. return result;
22. }
23.
24. public static void main(String[] args){
25. Computation[] computations = new Computation[4];
26. for(int i=0; i27. computations[i] = new Computation(i);
28. computations[i].start();
29. }
30. for(Computation c : computations)
31. System.out.print(c.getResult() + " ");
32. }
33. }
What is the result?
A. The code will deadlock.
B. The code may run with no output.
C. An exception is thrown at runtime.
D. The code may run with output "0 6".
E. The code may run with output "2 0 6 4".
F. The code may run with output "0 2 4 6".
答案:F
參考:13-4 執行緒的同步性與安全性
1. class Computation extends Thread{
2.
3. private int num;
4. private boolean isComplete;
5. private int result;
6.
7. public Computation(int num){this.num = num;}
8.
9. public synchronized void run(){
10. result = num * 2;
11. isComplete = true;
12. notify();
13. }
14.
15. public synchronized int getResult(){
16. while(!isComplete){
17. try{
18. wait();
19. }catch(InterruptedException e){}
20. }
21. return result;
22. }
23.
24. public static void main(String[] args){
25. Computation[] computations = new Computation[4];
26. for(int i=0; i
28. computations[i].start();
29. }
30. for(Computation c : computations)
31. System.out.print(c.getResult() + " ");
32. }
33. }
What is the result?
A. The code will deadlock.
B. The code may run with no output.
C. An exception is thrown at runtime.
D. The code may run with output "0 6".
E. The code may run with output "2 0 6 4".
F. The code may run with output "0 2 4 6".
答案:F
參考:13-4 執行緒的同步性與安全性
第232題
Given:
1. public class Threads5{
2. public static void main(String[] args){
3. new Thread(new Runnable(){
4. public void run(){
5. System.out.print("bar");
6. }}).start();
7. }
8. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "bar".
D. The code executes normally, but nothing prints.
答案:C
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
------------------------------------------
執行到start()時,會跑public void run(){
1. public class Threads5{
2. public static void main(String[] args){
3. new Thread(new Runnable(){
4. public void run(){
5. System.out.print("bar");
6. }}).start();
7. }
8. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "bar".
D. The code executes normally, but nothing prints.
答案:C
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
------------------------------------------
執行到start()時,會跑public void run(){
第238題
Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)
A. new Thread(){
public void run(){doStuff();}
};
B. new Thread(){
public void start(){doStuff();}
};
C new Thread(){
public void start(){doStuff();}
}.run();
D. new Thread(){
public void run(){doStuff();}
}.start();
E. new Thread(new Runnable(){
public void run(){doStuff();}
}).run();
F. new Thread(new Runnable(){
public void run(){doStuff();}
}).start();
答案:DF
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
A. new Thread(){
public void run(){doStuff();}
};
B. new Thread(){
public void start(){doStuff();}
};
C new Thread(){
public void start(){doStuff();}
}.run();
D. new Thread(){
public void run(){doStuff();}
}.start();
E. new Thread(new Runnable(){
public void run(){doStuff();}
}).run();
F. new Thread(new Runnable(){
public void run(){doStuff();}
}).start();
答案:DF
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
第231題
Given:
11. Runnable r = new Runnable(){
12. public void run(){
13. System.out.print("Cat");
14. }
15. };
16. Thread t = new Thread(r){
17. public void run(){
18. System.outprint("Dog");
19. }
20. };
21. t.start();
What is the result?
A. Cat
B. Dog
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.
答案:B
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
--------------------------------
17行改寫了12行.
11. Runnable r = new Runnable(){
12. public void run(){
13. System.out.print("Cat");
14. }
15. };
16. Thread t = new Thread(r){
17. public void run(){
18. System.outprint("Dog");
19. }
20. };
21. t.start();
What is the result?
A. Cat
B. Dog
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.
答案:B
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
--------------------------------
17行改寫了12行.
第230題
Given that t1 is a reference to a live thread, which is true?
A. The Thread.sleep() method can take t1 as an argument.
B. The Object.notify() method can take t1 as an argument.
C. The Thread.yield() method can take t1 as an argument.
D. The Thread.setPriority() method can take t1 as an argument.
E. The Object.notify() method arbitrarily chooses which thread to notify.
答案:E
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
-------------------------------------
E. notify() 任意喚醒一條執行緒.
A~D 的方法都不是拿t1作為參數.
A. The Thread.sleep() method can take t1 as an argument.
B. The Object.notify() method can take t1 as an argument.
C. The Thread.yield() method can take t1 as an argument.
D. The Thread.setPriority() method can take t1 as an argument.
E. The Object.notify() method arbitrarily chooses which thread to notify.
答案:E
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
-------------------------------------
E. notify() 任意喚醒一條執行緒.
A~D 的方法都不是拿t1作為參數.
第239題
Given:
1. public class TestOne{
2. public static void main(String[] args) throws Exception{
3. Thread.sleep(3000);
4. System.out.println("sleep");
5. }
6. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "sleep".
D. The code executes normally, but nothing is printed.
答案:C
參考:13-2 Java執行緒與Thread類別
1. public class TestOne{
2. public static void main(String[] args) throws Exception{
3. Thread.sleep(3000);
4. System.out.println("sleep");
5. }
6. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "sleep".
D. The code executes normally, but nothing is printed.
答案:C
參考:13-2 Java執行緒與Thread類別
第241題
Given:
1. public class Threads3 implements Runnable{
2. public void run(){
3. System.out.print("running");
4. }
5. public static void main(String[] args){
6. Thread t = new Thread(new Threads3());
7. t.run();
8. t.run();
9. t.start();
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".
答案:E
參考:13-3 Runnable介面
1. public class Threads3 implements Runnable{
2. public void run(){
3. System.out.print("running");
4. }
5. public static void main(String[] args){
6. Thread t = new Thread(new Threads3());
7. t.run();
8. t.run();
9. t.start();
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".
答案:E
參考:13-3 Runnable介面
第242題
Given:
public class NamedCounter{
private final String name;
private int count;
public NamedCounter(String name){this.name = name;}
public String getName(){return name;}
public void increment(){count++;}
public int getCount(){return count;}
public void reset(){count = 0;}
Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose
three.)
A. declare reset() using the synchronized keyword
B. declare getName() using the synchronized keyword
C. declare getCount() using the synchronized keyword
D. declare the constructor using the synchronized keyword
E. declare increment() using the synchronized keyword
答案:ACE
參考:13-3 Runnable介面
public class NamedCounter{
private final String name;
private int count;
public NamedCounter(String name){this.name = name;}
public String getName(){return name;}
public void increment(){count++;}
public int getCount(){return count;}
public void reset(){count = 0;}
Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose
three.)
A. declare reset() using the synchronized keyword
B. declare getName() using the synchronized keyword
C. declare getCount() using the synchronized keyword
D. declare the constructor using the synchronized keyword
E. declare increment() using the synchronized keyword
答案:ACE
參考:13-3 Runnable介面
第243題
Given that Triangle implements Runnable, and:
31. void go() throws Exception{
32. Thread t = new Thread(new Triangle());
33. t.start();
34. for(int x=1; x<100000; x++){
35. //insert code here
36. if(x%100 == 0) System.out.print("g");
37. }}
38. public void run(){
39. try{
40. for(int x=1; x<100000; x++){
41. //insert the same code here
42. if(x%100 == 0) System.out.print("t");
43. }
44. }catch(Exception e){}
45. }
Which two statements, inserted independently at both lines 35 and 41, tend to allow both threads to
temporarily pause and allow the other thread to execute? (Choose two.)
A. Thread.wait();
B. Thread.join();
C. Thread.yield();
D. Thread.sleep(1);
E. Thread.notify();
答案:CD
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
31. void go() throws Exception{
32. Thread t = new Thread(new Triangle());
33. t.start();
34. for(int x=1; x<100000; x++){
35. //insert code here
36. if(x%100 == 0) System.out.print("g");
37. }}
38. public void run(){
39. try{
40. for(int x=1; x<100000; x++){
41. //insert the same code here
42. if(x%100 == 0) System.out.print("t");
43. }
44. }catch(Exception e){}
45. }
Which two statements, inserted independently at both lines 35 and 41, tend to allow both threads to
temporarily pause and allow the other thread to execute? (Choose two.)
A. Thread.wait();
B. Thread.join();
C. Thread.yield();
D. Thread.sleep(1);
E. Thread.notify();
答案:CD
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
第244題
Given:
1. public class TestSeven extends Thread{
2. private static int x;
3. public synchronized void doThings(){
4. int current = x;
5. current++;
6. x = current;
7. }
8. public void run(){
9. doThings();
10. }
11. }
Which statement is true?
A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable "x" are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized(new Object()){} block would make the
class thread-safe.
答案:E
參考:13-4 執行緒的同步性與安全性
1. public class TestSeven extends Thread{
2. private static int x;
3. public synchronized void doThings(){
4. int current = x;
5. current++;
6. x = current;
7. }
8. public void run(){
9. doThings();
10. }
11. }
Which statement is true?
A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable "x" are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized(new Object()){} block would make the
class thread-safe.
答案:E
參考:13-4 執行緒的同步性與安全性
第229題
Given:
1. public class TestFive{
2. private int x;
3. public void foo(){
4. int current = x;
5. x = current + 1;
6. }
7. public void go(){
8. for(int i=0; i<5; i++){
9. new Thread(){
10. public void run(){
11. foo();
12. System.out.print(x + ", ");
13. }}.start();
14. }}
Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)
A. move the line 12 print statement into the foo() method
B. change line 7 to public synchronized void go(){
C. change the variable declaration on line 2 to private volatile int x;
D. wrap the code inside the foo() method with a synchronized(this) block
E. wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loop code here}
答案:AD
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
---------------------------------------
以題意來看同依時間只能有一個執行續執行.
A. 在原處的話,同時間有5條執行緒.
D. 在foo() 裡面使用 synchronize 區塊,這樣同時間就只能有一條執行緒.
1. public class TestFive{
2. private int x;
3. public void foo(){
4. int current = x;
5. x = current + 1;
6. }
7. public void go(){
8. for(int i=0; i<5; i++){
9. new Thread(){
10. public void run(){
11. foo();
12. System.out.print(x + ", ");
13. }}.start();
14. }}
Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)
A. move the line 12 print statement into the foo() method
B. change line 7 to public synchronized void go(){
C. change the variable declaration on line 2 to private volatile int x;
D. wrap the code inside the foo() method with a synchronized(this) block
E. wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loop code here}
答案:AD
參考:8-5-4 匿名內部類別、13-2 Java執行緒與Thread類別、13-3 Runnable介面
---------------------------------------
以題意來看同依時間只能有一個執行續執行.
A. 在原處的話,同時間有5條執行緒.
D. 在foo() 裡面使用 synchronize 區塊,這樣同時間就只能有一條執行緒.
第228題
Which three will compile and run without exception? (Choose three.)
A. private synchronized Object o;
B. void go(){
synchronized(){/* code here */}
C. public synchronized void go(){/* code here */}
D. private synchronized(this) void go(){/* code here */}
E. void go(){synchronized(Object.class){/* code here */}
F. void go(){Object o = new Object();
synchronized(o){/* code here */}
答案:CEF
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
-------------------------------------
E. 使用synchronize 區塊 鎖定類別.
F. 使用synchronize 區塊 鎖定物件.
A. private synchronized Object o;
B. void go(){
synchronized(){/* code here */}
C. public synchronized void go(){/* code here */}
D. private synchronized(this) void go(){/* code here */}
E. void go(){synchronized(Object.class){/* code here */}
F. void go(){Object o = new Object();
synchronized(o){/* code here */}
答案:CEF
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
-------------------------------------
E. 使用synchronize 區塊 鎖定類別.
F. 使用synchronize 區塊 鎖定物件.
第219題
Given:
1. public class Threads2 implements Runnable{
2.
3. public void run(){
4. System.out.println("run.");
5. throw new RuntimeException("Problem");
6. }
7. public static void main(String[] args){
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println("End of method.");
11. }
12. }
Which two can be results? (Choose two.)
A. java.lang.RuntimeException: Problem
B. run.
java.lang.RuntimeException: Problem
C. End of method.
java.lang.RuntimeException: Problem
D. End of method.
run.
java.lang.RuntimeException: Problem
E. run.
java.lang.RuntimeException: Problem
End of method.
答案:DE
參考:13-2 Java執行緒與Thread類別
1. public class Threads2 implements Runnable{
2.
3. public void run(){
4. System.out.println("run.");
5. throw new RuntimeException("Problem");
6. }
7. public static void main(String[] args){
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println("End of method.");
11. }
12. }
Which two can be results? (Choose two.)
A. java.lang.RuntimeException: Problem
B. run.
java.lang.RuntimeException: Problem
C. End of method.
java.lang.RuntimeException: Problem
D. End of method.
run.
java.lang.RuntimeException: Problem
E. run.
java.lang.RuntimeException: Problem
End of method.
答案:DE
參考:13-2 Java執行緒與Thread類別
第220題
Which factor or factors
A. It is possible for more than two threads to deadlock at once.
B. The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.
C. Deadlocked threads release once their sleep() method's sleep duration has expired.
D. Deadlocking can occur only when the wait(), notify() and notifyAll() methods are used incorrectly.
E. It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.
F. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking by
inserting invocations of Thread.yield().
答案:AF
參考:13-5 執行緒的互動處理
--------------------------------------------------------------
會有多條threads 進入deadlock
A. It is possible for more than two threads to deadlock at once.
B. The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.
C. Deadlocked threads release once their sleep() method's sleep duration has expired.
D. Deadlocking can occur only when the wait(), notify() and notifyAll() methods are used incorrectly.
E. It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.
F. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking by
inserting invocations of Thread.yield().
答案:AF
參考:13-5 執行緒的互動處理
--------------------------------------------------------------
會有多條threads 進入deadlock
第227題
Given:
1. public class TestOne implements Runnable{
2. public static void main (String[] args)throws Exception{
3. Thread t = new Thread(new TestOne());
4. t.start();
5. System.out.pririt("Started");
6. t.join();
7. System.out.print("Complete");
8. }
9. public void run(){
10. for(int i=0; i<4; i++){
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "StartedComplete".
D. The code executes and prints "StartedComplete0123".
E. The code executes and prints "Started0123Complete".
答案:E
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
------------------------------
t.join() 主執行緒 會等 副執行緒結束後再執行.
1. public class TestOne implements Runnable{
2. public static void main (String[] args)throws Exception{
3. Thread t = new Thread(new TestOne());
4. t.start();
5. System.out.pririt("Started");
6. t.join();
7. System.out.print("Complete");
8. }
9. public void run(){
10. for(int i=0; i<4; i++){
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "StartedComplete".
D. The code executes and prints "StartedComplete0123".
E. The code executes and prints "Started0123Complete".
答案:E
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
------------------------------
t.join() 主執行緒 會等 副執行緒結束後再執行.
第221題
Given:
7. void waitForSignal(){
8. Object obj = new Object();
9. synchronized(Thread.currentThread()){
10. obj.wait();
11. obj.notify();
12. }
13. }
Which statement is true?
A. This code can throw an InterruptedException.
B. This code can throw an IllegalMonitorStateException.
C. This code can throw a TimeoutException after ten minutes.
D. Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.
E. A call to notify() or notifyAll() from another thread might cause this method to complete normally.
F. This code does NOT compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".
答案:B
參考:13-5 執行緒的互動處理
----------------------------------------------------------
9. synchronized(Thread.currentThread()){
改9. synchronized(obj ){ 就ok
7. void waitForSignal(){
8. Object obj = new Object();
9. synchronized(Thread.currentThread()){
10. obj.wait();
11. obj.notify();
12. }
13. }
Which statement is true?
A. This code can throw an InterruptedException.
B. This code can throw an IllegalMonitorStateException.
C. This code can throw a TimeoutException after ten minutes.
D. Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.
E. A call to notify() or notifyAll() from another thread might cause this method to complete normally.
F. This code does NOT compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".
答案:B
參考:13-5 執行緒的互動處理
----------------------------------------------------------
9. synchronized(Thread.currentThread()){
改9. synchronized(obj ){ 就ok
第222題
Given:
10. public class Starter extends Thread{
11. private int x = 2;
12. public static void main(String[] args) throws Exception{
13. new Starter().makeItSo();
14. }
15. public Starter(){
16. x = 5;
17. start();
18. }
19. public void makeItSo() throws Exception{
20. join();
21. x = x - 1;
22. System.out.println(x);
23. }
24. public void run(){x *= 2;}
25. }
What is the output if the main() method is run?
A. 4
B. 5
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown at runhime.
G. It is impossible to determine for certain.
答案:D
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
----------------------------------------------------
17. start();//開第二條Thread
19. public void makeItSo() throws Exception{
20. join(); //等次Thread做完後才繼續
10. public class Starter extends Thread{
11. private int x = 2;
12. public static void main(String[] args) throws Exception{
13. new Starter().makeItSo();
14. }
15. public Starter(){
16. x = 5;
17. start();
18. }
19. public void makeItSo() throws Exception{
20. join();
21. x = x - 1;
22. System.out.println(x);
23. }
24. public void run(){x *= 2;}
25. }
What is the output if the main() method is run?
A. 4
B. 5
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown at runhime.
G. It is impossible to determine for certain.
答案:D
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面
----------------------------------------------------
17. start();//開第二條Thread
19. public void makeItSo() throws Exception{
20. join(); //等次Thread做完後才繼續
第223題
Given:
11. class PingPong2{
12. synchronized void hit(long n){
13. for(int i=1; i<3; i++)
14. System.out.print(n + "-" + i + " ");
15. }
16. }
17. public dass Tester implements Runnable{
18. static PingPong2 pp2 = new PingPong2();
19. public static void main(String[] args){
20. new Thread(new Tester()).start();
21. new Thread(new Tester()).start();
22. }
23. public void run(){pp2.hit(Thread.currentThread.getId());}
24. }
Which statement is true?
A. The output could be 5-1 6-1 6-2 5-2
B. The output could be 6-1 6-2 5-1 5-2
C. The output could be 6-1 5-2 6-2 5-1
D. The output could be 6-1 6-2 5-1 7-1
答案:B
參考:13-4 執行緒的同步性與安全性
-----------------------------------------------------------
透過synchronized 同時間只會執行一個hit的Thread,故選x-1 x-2 y-1 y-2
11. class PingPong2{
12. synchronized void hit(long n){
13. for(int i=1; i<3; i++)
14. System.out.print(n + "-" + i + " ");
15. }
16. }
17. public dass Tester implements Runnable{
18. static PingPong2 pp2 = new PingPong2();
19. public static void main(String[] args){
20. new Thread(new Tester()).start();
21. new Thread(new Tester()).start();
22. }
23. public void run(){pp2.hit(Thread.currentThread.getId());}
24. }
Which statement is true?
A. The output could be 5-1 6-1 6-2 5-2
B. The output could be 6-1 6-2 5-1 5-2
C. The output could be 6-1 5-2 6-2 5-1
D. The output could be 6-1 6-2 5-1 7-1
答案:B
參考:13-4 執行緒的同步性與安全性
-----------------------------------------------------------
透過synchronized 同時間只會執行一個hit的Thread,故選x-1 x-2 y-1 y-2
第226題
Which two statements are true? (Choose two.)
A. It is possible to synchronize static methods.
B. When a thread has yielded as a result of yield(), it releases its locks.
C. When a thread is sleeping as a result of sleep(), it releases its locks.
D. The Object.wait() method can be invoked only from a synchronized context.
E. The Thread.sleep() method can be invoked only from a synchronized context.
F. When the thread scheduler receives a notify() request, and notifies a thread, that thread immediately releases its lock.
答案:AD
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
--------------------------------------
A. synchronize 可以鎖定 static的方法
D. 如果要呼叫 wait() 必須要冠上synchronzie的內容, 例如 方法,或區塊.
A. It is possible to synchronize static methods.
B. When a thread has yielded as a result of yield(), it releases its locks.
C. When a thread is sleeping as a result of sleep(), it releases its locks.
D. The Object.wait() method can be invoked only from a synchronized context.
E. The Thread.sleep() method can be invoked only from a synchronized context.
F. When the thread scheduler receives a notify() request, and notifies a thread, that thread immediately releases its lock.
答案:AD
參考:13-2 Java執行緒與Thread類別、13-3 Runnable介面、13-5 執行緒的互動處理
--------------------------------------
A. synchronize 可以鎖定 static的方法
D. 如果要呼叫 wait() 必須要冠上synchronzie的內容, 例如 方法,或區塊.
第224題
Given:
1. public class Threads4{
2. public static void main(String[] args){
3. new Threads4.go();
4. }
5. public void go(){
6. Runnable r = new Runnable(){
7. public void run(){
8. System.out.print("foo");
9. }
10. };
11. Thread t = new Thread(r);
12. t.start();
13. t.start();
14. }
15. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "foo";
D. The code executes normally, but nothing is printed.
答案:B
參考:13-4 執行緒的同步性與安全性
------------------------------------------------
13. t.start(); //ERROR Thread 己經在12行產生了,
這行會產生exception IllegalThreadStateException
1. public class Threads4{
2. public static void main(String[] args){
3. new Threads4.go();
4. }
5. public void go(){
6. Runnable r = new Runnable(){
7. public void run(){
8. System.out.print("foo");
9. }
10. };
11. Thread t = new Thread(r);
12. t.start();
13. t.start();
14. }
15. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "foo";
D. The code executes normally, but nothing is printed.
答案:B
參考:13-4 執行緒的同步性與安全性
------------------------------------------------
13. t.start(); //ERROR Thread 己經在12行產生了,
這行會產生exception IllegalThreadStateException
第225題
Given:
10. Runnable r = new Runnable(){
11. public void run(){
12. try{
13. Thread.sleep(1000);
14. }catch(InterruptedException e){
15. System.out.println("interrupted");
16. }
17. System.out.println("ran");
18. }
19. };
20. Thread t = new Thread(r);
21. t.start();
22. System.out.println("started");
23. t.sleep(2000):
24. System.out.println("interrupting");
25. t.interrupt();
26. System.out.println("ended");
Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time.
Place the fragments in the output area to show the result of running this code.
10. Runnable r = new Runnable(){
11. public void run(){
12. try{
13. Thread.sleep(1000);
14. }catch(InterruptedException e){
15. System.out.println("interrupted");
16. }
17. System.out.println("ran");
18. }
19. };
20. Thread t = new Thread(r);
21. t.start();
22. System.out.println("started");
23. t.sleep(2000):
24. System.out.println("interrupting");
25. t.interrupt();
26. System.out.println("ended");
Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time.
Place the fragments in the output area to show the result of running this code.
答案:
Output
(no more output)
started
ran
interrupting
ended
參考:13-3 Runnable介面
---------------------------------
23. 主執行緒 睡2秒, 副執行緒稅1秒, 所以先印出ran 再印 interrupt.
第217題
第216題
Given:
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List list = new LinkedList();
5. list.add("one");
6. list.add("two");
7. System.out.print(((String)list.get(O)).length());
8. }
9. }
Refactor this class to use generics without changing the code's behavior.
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. Place here
5. list.add("one");
6. list.add("two");
7. Place here
8. }
9. }
Code:
List list = new LinkedList();
System.out.print(list.get(0).length());
List<String> list = new LinkedList<String>();
System.out.print(list.get<String>(0).length());
List<String> list = new LinkedList();
System.out.print(<String>list.get(0).length());
List list = new LinkedList<String>();
System.out.print((List<String>)list.get(0).length());
答案:
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List<String> list = new LinkedList<String>();
5. list.add("one");
6. list.add("two");
7. System.out.print(list.get(0).length());
8. }
9. }
參考:12-3 泛型
--------------------------------------
5,6行加入String, 所以泛型要限定為String,
7.行, 以限定為String, 印出就不用再轉型.
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List list = new LinkedList();
5. list.add("one");
6. list.add("two");
7. System.out.print(((String)list.get(O)).length());
8. }
9. }
Refactor this class to use generics without changing the code's behavior.
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. Place here
5. list.add("one");
6. list.add("two");
7. Place here
8. }
9. }
Code:
List list = new LinkedList();
System.out.print(list.get(0).length());
List<String> list = new LinkedList<String>();
System.out.print(list.get<String>(0).length());
List<String> list = new LinkedList();
System.out.print(<String>list.get(0).length());
List list = new LinkedList<String>();
System.out.print((List<String>)list.get(0).length());
答案:
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List<String> list = new LinkedList<String>();
5. list.add("one");
6. list.add("two");
7. System.out.print(list.get(0).length());
8. }
9. }
參考:12-3 泛型
--------------------------------------
5,6行加入String, 所以泛型要限定為String,
7.行, 以限定為String, 印出就不用再轉型.
第215題
Given:
1. import java.util.*;
2.
3. public class LetterASort{
4. public static void main(String[] args){
5. ArrayList strings = new ArrayList();
6. strings.add("aAaA");
7. strings.add("AaA");
8. strings.add("aAa");
9. strings.add("AAaa");
10. Collections.sort(strings);
11. for(String s : strings){System.out.print(s + " ");}
12. }
13. }
What is the result?
A. Compilation fails.
B. aAaA aAa AAaa AaA
C. AAaa AaA aAa aAaA
D. AaA AAaa aAaA aAa
E. aAa AaA aAaA AAaa
F. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
1. import java.util.*;
2.
3. public class LetterASort{
4. public static void main(String[] args){
5. ArrayList
6. strings.add("aAaA");
7. strings.add("AaA");
8. strings.add("aAa");
9. strings.add("AAaa");
10. Collections.sort(strings);
11. for(String s : strings){System.out.print(s + " ");}
12. }
13. }
What is the result?
A. Compilation fails.
B. aAaA aAa AAaa AaA
C. AAaa AaA aAa aAaA
D. AaA AAaa aAaA aAa
E. aAa AaA aAaA AAaa
F. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
第214題
Given:
12. import java.util.*;
13. public class Explorer3{
14. public static void main(String[] args){
15. TreeSet s = new TreeSet();
16. TreeSet subs = new TreeSet();
17. for(int i=606; i<613; i++)
18. if(i%2 == 0) s.add(i);
19. subs = (TreeSet)s.subSet(608, true, 611, true);
20. subs.add(629);
21. System.out.println(s + " " + subs);
22. }
23. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. [608, 610, 612, 629] [608, 610]
D. [608, 610, 612, 629] [608, 610, 629]
E. [606, 608, 610, 612, 629] [608, 610]
F. [606, 608, 610, 612, 629] [608, 610, 629]
答案:B
參考:12-4-4 子集檢視
---------------------------------------------
19. 設定子集檢視為608到611(含608和611),
20. 要加入629, 已超出範圍
12. import java.util.*;
13. public class Explorer3{
14. public static void main(String[] args){
15. TreeSet
16. TreeSet
17. for(int i=606; i<613; i++)
18. if(i%2 == 0) s.add(i);
19. subs = (TreeSet)s.subSet(608, true, 611, true);
20. subs.add(629);
21. System.out.println(s + " " + subs);
22. }
23. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. [608, 610, 612, 629] [608, 610]
D. [608, 610, 612, 629] [608, 610, 629]
E. [606, 608, 610, 612, 629] [608, 610]
F. [606, 608, 610, 612, 629] [608, 610, 629]
答案:B
參考:12-4-4 子集檢視
---------------------------------------------
19. 設定子集檢視為608到611(含608和611),
20. 要加入629, 已超出範圍
第213題
Given a class whose instances, when found in a collection of objects, are sorted by using the compareTo() method, which two statements are true? (choose two.)
A. The class implements java.lang.Comparable.
B. The class implements java.util.Comparator.
C. The interface used to implement sorting allows this class to define only one sort sequence.
D. The interface used to implement sorting allows this class to define many different sort sequences.
答案:AC
參考:12-4-3 SortedSet集合
---------------------------------------------
實作Comparable,並實作compareTo()的內容.
實作排序方法只能用一種排序方法. (實作順序,就不能用逆序).
A. The class implements java.lang.Comparable.
B. The class implements java.util.Comparator.
C. The interface used to implement sorting allows this class to define only one sort sequence.
D. The interface used to implement sorting allows this class to define many different sort sequences.
答案:AC
參考:12-4-3 SortedSet集合
---------------------------------------------
實作Comparable,並實作compareTo()的內容.
實作排序方法只能用一種排序方法. (實作順序,就不能用逆序).
第212題
Given:
3. import java.util.*;
4. public class Hancock{
5. //insert code here
6. list.add("foo");
7. }
8. }
Which two code fragments, inserted independently at line 5, will compile without warnings? (Choose two.)
A. public void addStrings(List list){
B. public void addStrings(List < String > list){
C. public void addStrings(List < ? super String > list){
D. public void addStrings(List < ? extends String > list){
答案:BC
參考:12-4-2 equals()、hashCode()方法的改寫
------------------------------------------------
使用泛型,
B 限定傳過來的list 型態為 String,
C 限定為 String 或 其父類別...至少可以用String.
D.不行是因為 限定為String得子類別, list.add("foo") 是加入String, 變成加入父類別.
3. import java.util.*;
4. public class Hancock{
5. //insert code here
6. list.add("foo");
7. }
8. }
Which two code fragments, inserted independently at line 5, will compile without warnings? (Choose two.)
A. public void addStrings(List list){
B. public void addStrings(List < String > list){
C. public void addStrings(List < ? super String > list){
D. public void addStrings(List < ? extends String > list){
答案:BC
參考:12-4-2 equals()、hashCode()方法的改寫
------------------------------------------------
使用泛型,
B 限定傳過來的list 型態為 String,
C 限定為 String 或 其父類別...至少可以用String.
D.不行是因為 限定為String得子類別, list.add("foo") 是加入String, 變成加入父類別.
第211題
Given:
11. public class Key{
12. private long id1,
13. private long id2;
14.
15. //class Key methods
16. }
A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap.
Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)
A. public int hashCode()
B. public void hashCode()
C. public int compareTo(Object o)
D. public boolean equals(Object o)
E. public boolean compareTo(Key k)
答案:AD
參考:12-4-2 equals()、hashCode()方法的改寫
-----------------------------------------------
Key 會先用hashCode 來比較, 如果得到的值一樣,無法分辨不同時就會用 equals.
hashCode 回傳是 int.
11. public class Key{
12. private long id1,
13. private long id2;
14.
15. //class Key methods
16. }
A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap.
Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)
A. public int hashCode()
B. public void hashCode()
C. public int compareTo(Object o)
D. public boolean equals(Object o)
E. public boolean compareTo(Key k)
答案:AD
參考:12-4-2 equals()、hashCode()方法的改寫
-----------------------------------------------
Key 會先用hashCode 來比較, 如果得到的值一樣,無法分辨不同時就會用 equals.
hashCode 回傳是 int.
2009年2月24日 星期二
第204題
Given:
11. public class Person{
12. private name;
13. public Person(String name){
14. this.name = name;
15. }
16. public int hashCode(){
17. return 420;
18. }
19. }
Which statement is true?
A. The time to find the value from HashMap with a Person key depends on the size of the map.
B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
C. Inserting a second Person object into a HashSet will cause the first Person object
to be removed as a duplicate.
D. The time to determine whether a Person object is contained in a HashSet is constant
and does NOT depend on the size of the map.
答案:A
參考:12-4-2 equals()、hashCode()方法的改寫
11. public class Person{
12. private name;
13. public Person(String name){
14. this.name = name;
15. }
16. public int hashCode(){
17. return 420;
18. }
19. }
Which statement is true?
A. The time to find the value from HashMap with a Person key depends on the size of the map.
B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
C. Inserting a second Person object into a HashSet will cause the first Person object
to be removed as a duplicate.
D. The time to determine whether a Person object is contained in a HashSet is constant
and does NOT depend on the size of the map.
答案:A
參考:12-4-2 equals()、hashCode()方法的改寫
第205題
Given:
12. import java.util.*;
13. public class Explorer2{
14. public static void main(String[] args){
15. TreeSet<Integer> s = new TreeSet<Integer>();
16. TreeSet<Integer> subs = new TreeSet<Integer>();
17. for(int i=606; i<613; i++)
18. if(i%2 == 0) s.add(i);
19. subs = (TreeSet)s.subSet(608, true, 611, true);
20. s.add(629);
21. System.out.println(s + " " + subs);
22. }
23. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. [608, 610, 612, 629] [608, 610]
D. [608, 610, 612, 629] [608, 610, 629]
E. [606, 608, 610, 612, 629] [608, 610]
F. [606, 608, 610, 612, 629] [608, 610, 629]
答案:E
參考:12-4-4 子集檢視
18. if(i%2 == 0) s.add(i); //只加入偶數
[606, 608, 610, 612] [608, 610]
20. s.add(629);
E. [606, 608, 610, 612, 629] [608, 610]
12. import java.util.*;
13. public class Explorer2{
14. public static void main(String[] args){
15. TreeSet<Integer> s = new TreeSet<Integer>();
16. TreeSet<Integer> subs = new TreeSet<Integer>();
17. for(int i=606; i<613; i++)
18. if(i%2 == 0) s.add(i);
19. subs = (TreeSet)s.subSet(608, true, 611, true);
20. s.add(629);
21. System.out.println(s + " " + subs);
22. }
23. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. [608, 610, 612, 629] [608, 610]
D. [608, 610, 612, 629] [608, 610, 629]
E. [606, 608, 610, 612, 629] [608, 610]
F. [606, 608, 610, 612, 629] [608, 610, 629]
答案:E
參考:12-4-4 子集檢視
18. if(i%2 == 0) s.add(i); //只加入偶數
[606, 608, 610, 612] [608, 610]
20. s.add(629);
E. [606, 608, 610, 612, 629] [608, 610]
第206題
Given:
1. public class Drink implements Comparable{
2. public String name;
3. public int compareTo(Object o){
4. return 0;
5. }
6. }
and:
20. Drink one = new Drink();
21. Drink two = new Drink();
22. one.name = "Coffee";
23. two.name = "Tea";
24. TreeSet set = new TreeSet();
25. set.add(one);
26. set.add(two);
A programmer iterates over the TreeSet and prints the name of each Drink object.
What is the result?
A. Tea
B. Coffee
C. Coffee Tea
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.
答案:B
參考:12-4-3 SortedSet集合
24. TreeSet set = new TreeSet(); //不可加入相同元素
25. set.add(one); //可加入
26. set.add(two); //視為同元素故不會加入,因為第3,4行
1. public class Drink implements Comparable{
2. public String name;
3. public int compareTo(Object o){
4. return 0;
5. }
6. }
and:
20. Drink one = new Drink();
21. Drink two = new Drink();
22. one.name = "Coffee";
23. two.name = "Tea";
24. TreeSet set = new TreeSet();
25. set.add(one);
26. set.add(two);
A programmer iterates over the TreeSet and prints the name of each Drink object.
What is the result?
A. Tea
B. Coffee
C. Coffee Tea
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.
答案:B
參考:12-4-3 SortedSet集合
24. TreeSet set = new TreeSet(); //不可加入相同元素
25. set.add(one); //可加入
26. set.add(two); //視為同元素故不會加入,因為第3,4行
第203題
Given:
5. import java.util.*;
6. public class SortOf{
7. public static void main(String[] args){
8. ArrayList a = new ArrayList();
9. a.add(1); a.add(5); a.add(3);
10. Collections.sort(a);
11. a.add(2);
12. Collections.reverse(a);
13. System.out.println(a);
14. }
15. }
What is the result?
A. [1, 2, 3, 5]
B. [2, 1, 3, 5]
C. [2, 5, 3, 1]
D. [5, 3, 2, 1]
E. [1, 3, 5, 2]
F. Compilation fails.
G. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
-------------------------------------------------
9. a.add(1); a.add(5); a.add(3); // ArrayList有順序性, 所以照順序加入 [1, 5, 3]
10. Collections.sort(a); // 排序, 變為 [1, 3, 5]
11. a.add(2); // 在加入 2 在最後面, [1, 3, 5, 2]
12. Collections.reverse(a); // 倒轉, [ 2, 5, 3, 1]
13. System.out.println(a); // output [2, 5, 3, 1]
5. import java.util.*;
6. public class SortOf{
7. public static void main(String[] args){
8. ArrayList
9. a.add(1); a.add(5); a.add(3);
10. Collections.sort(a);
11. a.add(2);
12. Collections.reverse(a);
13. System.out.println(a);
14. }
15. }
What is the result?
A. [1, 2, 3, 5]
B. [2, 1, 3, 5]
C. [2, 5, 3, 1]
D. [5, 3, 2, 1]
E. [1, 3, 5, 2]
F. Compilation fails.
G. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
-------------------------------------------------
9. a.add(1); a.add(5); a.add(3); // ArrayList有順序性, 所以照順序加入 [1, 5, 3]
10. Collections.sort(a); // 排序, 變為 [1, 3, 5]
11. a.add(2); // 在加入 2 在最後面, [1, 3, 5, 2]
12. Collections.reverse(a); // 倒轉, [ 2, 5, 3, 1]
13. System.out.println(a); // output [2, 5, 3, 1]
第207題
A programmer must create a generic class MinMax and the type parameter of MinMax must implement
Comparable. Which implementation of MinMax will compile?
A. class MinMax<E extends Comparable<E>>{
E min = null;
E max = null;
public MinMax(){}
public void put(E value){/* store min or max */}
B. class MinMax<E implements Comparable<E>>{
E min = null;
E max = null;
public MinMax(){}
public void put(E value){/* store min or max */}
C. class MinMax<E extends Comparable<E>>{
<E> E min = null;
<E> E max = null;
public MinMax(){}
public <E> void put(E value){/* store min or max */}
D. class MinMax<E implements Comparable<E>>{
<E> E min = null;
<E> E max = null;
public MinMax(){}
public <E> void put(E value){/* store min or max */}
答案:A
參考:12-3 泛型
-----------------------------------------------------
一個程式設計師想要做一個帶有泛型的類別 MinMax ,而且屬性想要用泛型且去實做Comparable,
照理說實做要用implement ,但在泛型不論是實做或繼承父介面一律用extends ,不可以用implement
Comparable. Which implementation of MinMax will compile?
A. class MinMax<E extends Comparable<E>>{
E min = null;
E max = null;
public MinMax(){}
public void put(E value){/* store min or max */}
B. class MinMax<E implements Comparable<E>>{
E min = null;
E max = null;
public MinMax(){}
public void put(E value){/* store min or max */}
C. class MinMax<E extends Comparable<E>>{
<E> E min = null;
<E> E max = null;
public MinMax(){}
public <E> void put(E value){/* store min or max */}
D. class MinMax<E implements Comparable<E>>{
<E> E min = null;
<E> E max = null;
public MinMax(){}
public <E> void put(E value){/* store min or max */}
答案:A
參考:12-3 泛型
-----------------------------------------------------
一個程式設計師想要做一個帶有泛型的類別 MinMax ,而且屬性想要用泛型且去實做Comparable,
照理說實做要用implement ,但在泛型不論是實做或繼承父介面一律用extends ,不可以用implement
第208題
Given:
1. import java.util.*;
2. public class Example{
3. public static void main(String[] args){
4. //insert code here
5. set.add(new Integer(2));
6. set.add(new Integer(1)),
7. System.out.println(set);
8. }
9. }
Which code, inserted at line 4, guarantees that this program will output [1, 2]?
A. Set set = new TreeSet();
B. Set set = new HashSet();
C. Set set = new SortedSet();
D. List set = new SortedList();
E. Set set = new LinkedHashSet();
答案:A
參考:12-4-3 SortedSet集合
1. import java.util.*;
2. public class Example{
3. public static void main(String[] args){
4. //insert code here
5. set.add(new Integer(2));
6. set.add(new Integer(1)),
7. System.out.println(set);
8. }
9. }
Which code, inserted at line 4, guarantees that this program will output [1, 2]?
A. Set set = new TreeSet();
B. Set set = new HashSet();
C. Set set = new SortedSet();
D. List set = new SortedList();
E. Set set = new LinkedHashSet();
答案:A
參考:12-4-3 SortedSet集合
第209題
Given:
1. import java.util.*;
2. public class TestSet{
3. enum Example{ONE, TWO, THREE}
4. public static void main(String[] args){
5. Collection coll = new ArrayList();
6. coll.add(Example.THREE);
7. coll.add(Example.THREE);
8. coll.add(Example.THREE);
9. coll.add(Example.TWO);
10. coll.add(Example.TWO);
11. coll.add(Example.ONE)
12. Set set = new HashSet(coll);
13. }
14. }
Which statement is true about the set variable on line 12?
A. The set variable contains all six elements from the coll collection, and the order is guaranteed to be
preserved.
B. The set variable contains only three elements from the coll collection, and the order is guaranteed to be
preserved.
C. The set variable contains all six elements from the coll collection, but the order is NOT guaranteed to be
preserved.
D. The set variable contains only three elements from the coll collection, but the order is NOT guaranteed
to be preserved.
答案:D
參考:12-4-1 Set集合、12-4-5 List集合
-----------------------------------------------------------------
6. coll.add(Example.THREE);
7. coll.add(Example.THREE);
8. coll.add(Example.THREE);
9. coll.add(Example.TWO);
10. coll.add(Example.TWO);
11. coll.add(Example.ONE)
都會放入coll中共6個
12. Set set = new HashSet(coll); //一樣的不給放,所以只有三個可放入,但沒有順序的依據
1. import java.util.*;
2. public class TestSet{
3. enum Example{ONE, TWO, THREE}
4. public static void main(String[] args){
5. Collection coll = new ArrayList();
6. coll.add(Example.THREE);
7. coll.add(Example.THREE);
8. coll.add(Example.THREE);
9. coll.add(Example.TWO);
10. coll.add(Example.TWO);
11. coll.add(Example.ONE)
12. Set set = new HashSet(coll);
13. }
14. }
Which statement is true about the set variable on line 12?
A. The set variable contains all six elements from the coll collection, and the order is guaranteed to be
preserved.
B. The set variable contains only three elements from the coll collection, and the order is guaranteed to be
preserved.
C. The set variable contains all six elements from the coll collection, but the order is NOT guaranteed to be
preserved.
D. The set variable contains only three elements from the coll collection, but the order is NOT guaranteed
to be preserved.
答案:D
參考:12-4-1 Set集合、12-4-5 List集合
-----------------------------------------------------------------
6. coll.add(Example.THREE);
7. coll.add(Example.THREE);
8. coll.add(Example.THREE);
9. coll.add(Example.TWO);
10. coll.add(Example.TWO);
11. coll.add(Example.ONE)
都會放入coll中共6個
12. Set set = new HashSet(coll); //一樣的不給放,所以只有三個可放入,但沒有順序的依據
第202題
Given:
NumberNames nn = new NumberNames();
nn.put("one", 1);
System.out.println(nn.getNames());
Place the code into position to create a class that maps from Strings to integer values. The result of execution must be [one]. Some options may be used more than once.
答案:
NumberNames nn = new NumberNames();
nn.put("one", 1);
System.out.println(nn.getNames());
Place the code into position to create a class that maps from Strings to integer values. The result of execution must be [one]. Some options may be used more than once.
答案:
參考:12-5-1 HashMap
----------------------------------
泛型使用不可以用基本型態, 所以 int 要放入 Integer.
第210題
Given:
11. public class Person{
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c){
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o){
18. if (!(0 instanceof Person)) return false;
19. Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }
What is the appropriate definition of the hashCode method in class Person?
A. return super.hashCode();
B. return name.hashcode() + age * 7;
C. return name.hashCode() + comment.hashCode() / 2;
D. return name.hashCode() + comment.hashCode() / 2- age * 3;
答案:D
參考:12-4-2 equals()、hashCode()方法的改寫
-----------------------------------------------------------------
將所有的屬性放入改寫會比較恰當
11. public class Person{
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c){
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o){
18. if (!(0 instanceof Person)) return false;
19. Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }
What is the appropriate definition of the hashCode method in class Person?
A. return super.hashCode();
B. return name.hashcode() + age * 7;
C. return name.hashCode() + comment.hashCode() / 2;
D. return name.hashCode() + comment.hashCode() / 2- age * 3;
答案:D
參考:12-4-2 equals()、hashCode()方法的改寫
-----------------------------------------------------------------
將所有的屬性放入改寫會比較恰當
第196題
Given:
34. HashMap props = new HashMap();
35. props.put("key45", "some value");
36. props.put("keyl2", "some other value");
37. props.put("key39", "yet another value");
38. Set s = props.keySet();
39. //insert code here
What inserted at line 39, will sort the keys in the props HashMap?
A. Arrays.sort(s);
B. s = new TreeSet(s);
C. Collections.sort(s);
D. s = new SortedSet(s);
答案:B
參考:12-4-3 SortedSet集合、12-5-1 HashMap
--------------------------------------------
C. Collections.sort(s); //s要為list才可以,不能用set
34. HashMap props = new HashMap();
35. props.put("key45", "some value");
36. props.put("keyl2", "some other value");
37. props.put("key39", "yet another value");
38. Set s = props.keySet();
39. //insert code here
What inserted at line 39, will sort the keys in the props HashMap?
A. Arrays.sort(s);
B. s = new TreeSet(s);
C. Collections.sort(s);
D. s = new SortedSet(s);
答案:B
參考:12-4-3 SortedSet集合、12-5-1 HashMap
--------------------------------------------
C. Collections.sort(s); //s要為list才可以,不能用set
第195題
Given:
3. import java.util.*;
4. public class Mapit{
5. public static void main(String[] args){
6. Set set = new HashSet();
7. Integer i1 = 45;
8. Integer i2 = 46;
9. set.add(i1);
10. set.add(i1);
11. set.add(i2); System.out.print(set.size() + " ");
12. set.remove(i1); System.out.print(set.size() + " ");
13. i2 = 47;
14. set.remove(i2); System.out.print(set.size() + " ");
15. }
16. }
What is the result?
A. 2 1 0
B. 2 1 1
C. 3 2 1
D. 3 2 2
E. Compilation fails.
F. An exception is thrown at runtime.
答案:B
參考:12-4-1 Set集合
-------------------------------------------------------------
6. Set set = new HashSet();
9. set.add(i1);
10. set.add(i1);//不會放入,所以set到此只有一個元素
11. set.add(i2); System.out.print(set.size() + " "); //會放入所以有二元素
12. set.remove(i1); System.out.print(set.size() + " "); //移除一個元素所以剩一個元素
13. i2 = 47; //指的是i2 =new Integer(47);但set中的元素還是46
14. set.remove(i2); //set中沒有47這一個元素可以移除
3. import java.util.*;
4. public class Mapit{
5. public static void main(String[] args){
6. Set
7. Integer i1 = 45;
8. Integer i2 = 46;
9. set.add(i1);
10. set.add(i1);
11. set.add(i2); System.out.print(set.size() + " ");
12. set.remove(i1); System.out.print(set.size() + " ");
13. i2 = 47;
14. set.remove(i2); System.out.print(set.size() + " ");
15. }
16. }
What is the result?
A. 2 1 0
B. 2 1 1
C. 3 2 1
D. 3 2 2
E. Compilation fails.
F. An exception is thrown at runtime.
答案:B
參考:12-4-1 Set集合
-------------------------------------------------------------
6. Set
9. set.add(i1);
10. set.add(i1);//不會放入,所以set到此只有一個元素
11. set.add(i2); System.out.print(set.size() + " "); //會放入所以有二元素
12. set.remove(i1); System.out.print(set.size() + " "); //移除一個元素所以剩一個元素
13. i2 = 47; //指的是i2 =new Integer(47);但set中的元素還是46
14. set.remove(i2); //set中沒有47這一個元素可以移除
第201題
Given:
1. import java.util.*;
2. class A{}
3. class B extends A{}
4. public class Test{
5. public static void main(Strang[] args){
6. List<> listA = new LinkedList<>();
7. List<> listB = new LinkedList<>();
8. List<> listO = new LinkedList<>();
9. //insert code here
10. }
11. public static void m1(List list){}
12. public static void m2(List<> list){}
Place a result onto each method call to indicate what would happen if the method call were inserted at line 9.
Note: Results can be used more than once.
Method Calls:
m1(listA); m2(listA);
m1(listB); m2(listB);
m1(listO); m2(listO);
Result :
Does not compile.
Compiles and runs without error.
An exception is thrown at runtime.
答案:
m1(listA); Compiles and runs without error.
m1(listB); Compiles and runs without error.
m1(listO); Does not compile.
m2(listA); Compiles and runs without error.
m2(listB); Does not compile.
m2(listO); Does not compile.
參考:12-3 泛型
-------------------------------
泛型在方法傳遞值時, 並需要完成相等 除非是用 ? extends 或 ? super
void m1(List list){} //開放類別A 或其子類別.
m1(listA); // A 或 A的子類別.
m1(listB); // B有繼承A並且A的子類別.
m1(listO); // Object 不是 A的子類別.
m2(List<> list ) {} //只開放 類別A
m2(listA); . // 傳遞類別為 A
m2(listB); . // 雖然有繼承A , 但是m2 並沒有開放子類別.
m2(listO); . // listO 類別為 Object, 所以失敗
1. import java.util.*;
2. class A{}
3. class B extends A{}
4. public class Test{
5. public static void main(Strang[] args){
6. List<> listA = new LinkedList<>();
7. List<> listB = new LinkedList<>();
8. List<> listO = new LinkedList<>();
9. //insert code here
10. }
11. public static void m1(List list){}
12. public static void m2(List<> list){}
Place a result onto each method call to indicate what would happen if the method call were inserted at line 9.
Note: Results can be used more than once.
Method Calls:
m1(listA); m2(listA);
m1(listB); m2(listB);
m1(listO); m2(listO);
Result :
Does not compile.
Compiles and runs without error.
An exception is thrown at runtime.
答案:
m1(listA); Compiles and runs without error.
m1(listB); Compiles and runs without error.
m1(listO); Does not compile.
m2(listA); Compiles and runs without error.
m2(listB); Does not compile.
m2(listO); Does not compile.
參考:12-3 泛型
-------------------------------
泛型在方法傳遞值時, 並需要完成相等 除非是用 ? extends 或 ? super
void m1(List list){} //開放類別A 或其子類別.
m1(listA); // A 或 A的子類別.
m1(listB); // B有繼承A並且A的子類別.
m1(listO); // Object 不是 A的子類別.
m2(List<> list ) {} //只開放 類別A
m2(listA); . // 傳遞類別為 A
m2(listB); . // 雖然有繼承A , 但是m2 並沒有開放子類別.
m2(listO); . // listO 類別為 Object, 所以失敗
第194題
Given:
enum Example{ONE, TWO, THREE}
Which statement is true?
A. The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.
B. The expression (ONE < TWO) is guaranteed to be true and ONE.compareTo(TWO) is guaranteed to be
less than one.
C. The Example values cannot be used in a raw javautil.HashMap; instead, the programmer must use a
java.util.EnumMap.
D. The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because
enumerated types do NOT implement java.lang.Comparable.
答案:A
參考:8-6 Java列舉類型、12-4-3 SortedSet集合、12-5-1 HashMap
enum Example{ONE, TWO, THREE}
Which statement is true?
A. The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.
B. The expression (ONE < TWO) is guaranteed to be true and ONE.compareTo(TWO) is guaranteed to be
less than one.
C. The Example values cannot be used in a raw javautil.HashMap; instead, the programmer must use a
java.util.EnumMap.
D. The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because
enumerated types do NOT implement java.lang.Comparable.
答案:A
參考:8-6 Java列舉類型、12-4-3 SortedSet集合、12-5-1 HashMap
第200題
Given:
11. public class Person{
12. private String name;
13. public Person(String name){
14. this.name = name;
15. }
16. public boolean equals(Object o){
17. if(!(o instanceof Person)) return false;
18. Person p = (Person)o;
19. return p.name.equals(this.name);
20. }
21. }
Which statement is true?
A. Compilation fails because the hashCode method is not overridden.
B. A HashSet could contain multiple Person objects with the same name.
C. All Person objects will have the same hash code because the hashCode method is not overridden.
D. If a HashSet contains more than one Person object with name="Fred", then removing another Person, also with name="Fred", will remove them all.
答案:B
參考:12-4-2 equals()、hashCode()方法的改寫
----------------------------------------
因為沒有改寫hashCode, 所以相同名稱也會被視為不相同的物件, 所以可以全部放入hashSet
11. public class Person{
12. private String name;
13. public Person(String name){
14. this.name = name;
15. }
16. public boolean equals(Object o){
17. if(!(o instanceof Person)) return false;
18. Person p = (Person)o;
19. return p.name.equals(this.name);
20. }
21. }
Which statement is true?
A. Compilation fails because the hashCode method is not overridden.
B. A HashSet could contain multiple Person objects with the same name.
C. All Person objects will have the same hash code because the hashCode method is not overridden.
D. If a HashSet contains more than one Person object with name="Fred", then removing another Person, also with name="Fred", will remove them all.
答案:B
參考:12-4-2 equals()、hashCode()方法的改寫
----------------------------------------
因為沒有改寫hashCode, 所以相同名稱也會被視為不相同的物件, 所以可以全部放入hashSet
第193題
Give n that the elements of a PriorityQueue are ordered according to natural ordering, and:
2. import java.util.*;
3. public class GetInLine{
4. public static void main(String[] args){
5. PriorityQueue pq = new PriorityQueue();
6. pq.add("banana");
7. pq.add("pear");
8. pq.add("apple");
9. System.out.println(pq.poll() + " " + pq.peek());
10. }
11. }
What is the result?
A. apple pear
B. banana pear
C. apple apple
D. apple banana
E. banana banana
答案:D
參考:12-4-6 Queue集合
-------------------------------------------------------
5. PriorityQueue pq = new PriorityQueue();
6. pq.add("banana");
7. pq.add("pear");
8. pq.add("apple");
PriorityQueue會先把放入的東西做升冪排序,再做先進先出的方式排序
順序為apple/banana/pear
pq.poll()//指的是把元素值取出,並從集合中移除該元素,
pq.peek()//只會取出下一個元素的值不會移除該元素
2. import java.util.*;
3. public class GetInLine{
4. public static void main(String[] args){
5. PriorityQueue
6. pq.add("banana");
7. pq.add("pear");
8. pq.add("apple");
9. System.out.println(pq.poll() + " " + pq.peek());
10. }
11. }
What is the result?
A. apple pear
B. banana pear
C. apple apple
D. apple banana
E. banana banana
答案:D
參考:12-4-6 Queue集合
-------------------------------------------------------
5. PriorityQueue
6. pq.add("banana");
7. pq.add("pear");
8. pq.add("apple");
PriorityQueue
順序為apple/banana/pear
pq.poll()//指的是把元素值取出,並從集合中移除該元素,
pq.peek()//只會取出下一個元素的值不會移除該元素
第192題
Given:
3. import java.util.*;
4. public class G1{
5. public void takeList(List list){
6. //insert code here
7. }
8. }
Which three code fragments, inserted independently at line 6, will compile? (Choose three.)
A. list.add("foo");
B. Object o = list;
C. String s = list.get(0);
D. list = new ArrayList(string)();
E. list = new ArrayList(object)();
答案:BCD
參考:7-8 物件的轉型、12-3 泛型
3. import java.util.*;
4. public class G1{
5. public void takeList(List list){
6. //insert code here
7. }
8. }
Which three code fragments, inserted independently at line 6, will compile? (Choose three.)
A. list.add("foo");
B. Object o = list;
C. String s = list.get(0);
D. list = new ArrayList(string)();
E. list = new ArrayList(object)();
答案:BCD
參考:7-8 物件的轉型、12-3 泛型
第199題
Given
:
10. interface A{void x();}
11. class B implements A{public void x(){} public void y(){}}
12. class C extends B{public void x(){}}
And:
20. java.util.List<> list = new java.util.ArrayList<>();
21. list.add(new B());
22. list.add(new C());
23. for(A a : list){
24. a.x();
25. a.y();
26. }
What is the result?
A. The code runs with no output.
B. An exception is thrown at runtime.
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 23.
F. Compilation fails because of an error in line 25.
答案:F
參考:7-9 多型、12-4-5 List集合
--------------------------------------
20行建立一個List, 泛型
21,22 加入B 跟 C 元素. (B 實作A, C繼承B. 所以是A的子類別, 並在加入時自動轉型為A).
25. a.y(); 因 a 在23行宣告為 A. 所以會去找 interface A底下的y(). 並沒有此方法.
:
10. interface A{void x();}
11. class B implements A{public void x(){} public void y(){}}
12. class C extends B{public void x(){}}
And:
20. java.util.List<> list = new java.util.ArrayList<>();
21. list.add(new B());
22. list.add(new C());
23. for(A a : list){
24. a.x();
25. a.y();
26. }
What is the result?
A. The code runs with no output.
B. An exception is thrown at runtime.
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 23.
F. Compilation fails because of an error in line 25.
答案:F
參考:7-9 多型、12-4-5 List集合
--------------------------------------
20行建立一個List, 泛型
21,22 加入B 跟 C 元素. (B 實作A, C繼承B. 所以是A的子類別, 並在加入時自動轉型為A).
25. a.y(); 因 a 在23行宣告為 A. 所以會去找 interface A底下的y(). 並沒有此方法.
第191題
Given:
11. //insert code here
12. private N min, max;
13. public N getMin() { return min; }
14. public N getMax() { return max; }
15. public void add(N added) {
16. if(min == null added.doubleValue() < min =" added;" max ="=""> max.doubleValue())
19. max = added;
20. }
21. }
Which two, inserted at line 11, will allow the code to compile? (Choose two.)
A. public class MinMax{
B. public class MinMax{
C. public class MinMax{
D. public class MinMax{
E. public class MinMax{
F. public class MinMax{
答案:DF
參考:11-1-2 Wrapper類別、12-3 泛型
11. //insert code here
12. private N min, max;
13. public N getMin() { return min; }
14. public N getMax() { return max; }
15. public void add(N added) {
16. if(min == null added.doubleValue() < min =" added;" max ="=""> max.doubleValue())
19. max = added;
20. }
21. }
Which two, inserted at line 11, will allow the code to compile? (Choose two.)
A. public class MinMax{
B. public class MinMax{
C. public class MinMax
D. public class MinMax
E. public class MinMax{
F. public class MinMax
答案:DF
參考:11-1-2 Wrapper類別、12-3 泛型
第198題
Given:
11. public static Iterator reverse(List list){
12. Collections.reverse(list);
13. return list.iterator();
14. }
15. public static void main(String[] args){
16. List list= new ArrayList();
17. list.add("1"); list.add("2"); list.add("3");
18. for(Object obj : reverse(list))
19. System.out.print(obj + ", ");
20. }
What is the result?
A. 3, 2, 1,
B. 1, 2, 3,
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
-----------------------------------------------
18行跑 for each, 呼叫reverse,傳入list.
回傳iterator, 因 for each 不能用iterator物件, 所以編譯失敗.
11. public static Iterator reverse(List list){
12. Collections.reverse(list);
13. return list.iterator();
14. }
15. public static void main(String[] args){
16. List list= new ArrayList();
17. list.add("1"); list.add("2"); list.add("3");
18. for(Object obj : reverse(list))
19. System.out.print(obj + ", ");
20. }
What is the result?
A. 3, 2, 1,
B. 1, 2, 3,
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.
答案:C
參考:12-2-2 Collections類別、12-4-5 List集合
-----------------------------------------------
18行跑 for each, 呼叫reverse,傳入list.
回傳iterator, 因 for each 不能用iterator物件, 所以編譯失敗.
第190題
Given:
1. import java.util.*;
2. public class WrappedString{
3. private String s;
4. public WrappedString(String s){this.s = s;}
5. public static void main(String[] args){
6. HashSet(object) hs = new HashSet(object)();
7. WrappedString ws1 = new WrappedString("aardvark");
8. WrappedString ws2 = new WrappedString("aardvark");
9. String s1 = new String("aardvark");
10. String s2 = new String("aardvark");
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
12. System.out.println(hs.size()); }}
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.
答案:D
參考:12-4-2 equals()、hashCode()方法的改寫
1. import java.util.*;
2. public class WrappedString{
3. private String s;
4. public WrappedString(String s){this.s = s;}
5. public static void main(String[] args){
6. HashSet(object) hs = new HashSet(object)();
7. WrappedString ws1 = new WrappedString("aardvark");
8. WrappedString ws2 = new WrappedString("aardvark");
9. String s1 = new String("aardvark");
10. String s2 = new String("aardvark");
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
12. System.out.println(hs.size()); }}
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.
答案:D
參考:12-4-2 equals()、hashCode()方法的改寫
第197題
Given:
11. public static Collection get(){
12. Collection sorted = new LinkedList();
13. sorted.add("B"); sorted.add("C"); sorted.add("A");
14. return sorted;
15. }
16. public static void main(String[] args){
17. for(Object obj : get()){
18. System.out.print(obj + ", ");
19. }
20. }
What is the result?
A. A, B, C,
B. B, C, A,
C. Compilation fails.
D. The code runs with no output
E. An exception is thrown at runtime.
答案:B
參考:12-4-5 List集合
-----------------------
sorted 是LinkList... 直接加 B C A 並回傳
11. public static Collection get(){
12. Collection sorted = new LinkedList();
13. sorted.add("B"); sorted.add("C"); sorted.add("A");
14. return sorted;
15. }
16. public static void main(String[] args){
17. for(Object obj : get()){
18. System.out.print(obj + ", ");
19. }
20. }
What is the result?
A. A, B, C,
B. B, C, A,
C. Compilation fails.
D. The code runs with no output
E. An exception is thrown at runtime.
答案:B
參考:12-4-5 List集合
-----------------------
sorted 是LinkList... 直接加 B C A 並回傳
2009年2月23日 星期一
第188題
Given
a pre-generics implementation of a method:
11. public static int sum(List list){
12. int sum = 0;
13. for(Iterator iter = list.iterator(); iter.hasNext();){
14. int i = ((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
What three changes allow the class to be used with generics and avoid an unchecked warning? (Choose three.)
A. Remove line 14.
B. Replace line 14 with "int i = iter.next();".
C. Replace line 13 with "for(int i : intList){".
D. Replace line 13 with "for(Iterator iter : intList){".
E. Replace the method declaration with "sum(List < int > intList)".
F. Replace the method declaration with "sum(List < Integer > ntList)".
答案:ACF
參考:12-3 泛型
a pre-generics implementation of a method:
11. public static int sum(List list){
12. int sum = 0;
13. for(Iterator iter = list.iterator(); iter.hasNext();){
14. int i = ((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
What three changes allow the class to be used with generics and avoid an unchecked warning? (Choose three.)
A. Remove line 14.
B. Replace line 14 with "int i = iter.next();".
C. Replace line 13 with "for(int i : intList){".
D. Replace line 13 with "for(Iterator iter : intList){".
E. Replace the method declaration with "sum(List < int > intList)".
F. Replace the method declaration with "sum(List < Integer > ntList)".
答案:ACF
參考:12-3 泛型
第189題
Given
:
23. Object[] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i < myObjects.length; i++){
31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result?
A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.
答案:C
參考:5-4 1維陣列的排序與搜尋、12-2-2 Collections類別
:
23. Object[] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i < myObjects.length; i++){
31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result?
A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.
答案:C
參考:5-4 1維陣列的排序與搜尋、12-2-2 Collections類別
第187題
Given
:
1. public class Score implements Comparable{
2. private int wins, losses;
3. public Score(int w, int l){wins = w; losses = l;}
4. public int getWins(){return wins;}
5. public int getLosses(){return losses;}
6. public String toString(){
7. return "<" + wins + "," + losses + ">";
8. }
9. //insert code here
10. }
Which method will complete this class?
A. public int compareTo(Object o){/* more code here */}
B. public int compareTo(Score other){/* more code here */}
C. public int compare(Score s1, Score s2){/* more code here */}
D. public int compare(Object o1, Object o2){/* more code here */}
答案:B
參考:12-4 各種集合的特色
--------------------------------
實作Comparable, 泛型限制 為Score, 所以實作 compareTo時要用Score
:
1. public class Score implements Comparable
2. private int wins, losses;
3. public Score(int w, int l){wins = w; losses = l;}
4. public int getWins(){return wins;}
5. public int getLosses(){return losses;}
6. public String toString(){
7. return "<" + wins + "," + losses + ">";
8. }
9. //insert code here
10. }
Which method will complete this class?
A. public int compareTo(Object o){/* more code here */}
B. public int compareTo(Score other){/* more code here */}
C. public int compare(Score s1, Score s2){/* more code here */}
D. public int compare(Object o1, Object o2){/* more code here */}
答案:B
參考:12-4 各種集合的特色
--------------------------------
實作Comparable, 泛型限制 為Score, 所以實作 compareTo時要用Score
第186題
Which
two statements are true about the hashCode method? (Choose two.)
A. The hashCode method for a given class can be used to test for object equality and object inequality for that class.
B. The hashCode method is used by the java.util.SortedSet collection class to order the elements within that set.
C. The hashCode method for a given class can be used to test for object inequality, but NOT object equality, for that class.
D. The only important characteristic of the values returned by a hashCode method is that the distribution of values must follow a Gaussian distribution.
E. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.
答案:CE
參考:12-4 各種集合的特色
--------------------------------------------------
C. hashCode檢查兩各物件是否不相同, 如果可能相同再用equals檢查是否相同.
E. hashCode用來幫助hashset增加存取速度.
two statements are true about the hashCode method? (Choose two.)
A. The hashCode method for a given class can be used to test for object equality and object inequality for that class.
B. The hashCode method is used by the java.util.SortedSet collection class to order the elements within that set.
C. The hashCode method for a given class can be used to test for object inequality, but NOT object equality, for that class.
D. The only important characteristic of the values returned by a hashCode method is that the distribution of values must follow a Gaussian distribution.
E. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.
答案:CE
參考:12-4 各種集合的特色
--------------------------------------------------
C. hashCode檢查兩各物件是否不相同, 如果可能相同再用equals檢查是否相同.
E. hashCode用來幫助hashset增加存取速度.
第185題
Given:
1. public class Person{
2. private String name;
3. public Person(String name){this.name = name;}
4. public boolean equals(Person p){
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?
A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.
答案:A
參考:12-4 各種集合的特色
1. public class Person{
2. private String name;
3. public Person(String name){this.name = name;}
4. public boolean equals(Person p){
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?
A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.
答案:A
參考:12-4 各種集合的特色
第184題
第183題
Place the code in the appropriate places such that this program will always output [1, 2].
import java.util.*;
public class MyInt Place here Place here {
public static void main(String[] args){
ArrayList list = new ArrayList();
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
Place here int Place here {
MyInt i2 = (MyInt)o;
return Place here ;
}
}
Code:
implements, extends, sortable, Object, Comparable
protected, public,
i – i2.i,
i,
i2.i – i,
compare(MyInt o, MyInt i2), compare(Object o, Object i2)
sort(Object o), sort(MyInt o),
compareTo(MyInt o), compareTo(Object o)
答案:
import java.util.*;
public class MyInt implements Comparable {
public static void main(String[] args){
ArrayList list = new ArrayList();
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
public int compareTo(Object o) {
MyInt i2 = (MyInt)o;
return i - i2.i ;
}
}
參考:12-4-3 SortedSet集合
-----------------------------------
要做排序就必須implements Comparable, 然後實作 Comparable 裡面的 compareTo.
第二各放入的物件會自動放進compareTo做比較.
並print 會自動呼叫toString()
import java.util.*;
public class MyInt Place here Place here {
public static void main(String[] args){
ArrayList
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
Place here int Place here {
MyInt i2 = (MyInt)o;
return Place here ;
}
}
Code:
implements, extends, sortable, Object, Comparable
protected, public,
i – i2.i,
i,
i2.i – i,
compare(MyInt o, MyInt i2), compare(Object o, Object i2)
sort(Object o), sort(MyInt o),
compareTo(MyInt o), compareTo(Object o)
答案:
import java.util.*;
public class MyInt implements Comparable {
public static void main(String[] args){
ArrayList
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i){this.i = i;}
public String toString(){return Integer.toString(i);}
public int compareTo(Object o) {
MyInt i2 = (MyInt)o;
return i - i2.i ;
}
}
參考:12-4-3 SortedSet集合
-----------------------------------
要做排序就必須implements Comparable, 然後實作 Comparable 裡面的 compareTo.
第二各放入的物件會自動放進compareTo做比較.
並print 會自動呼叫toString()
2009年2月20日 星期五
第175題
Which two scenarios are NOT safe to replace a StringBuffer object with a StringBuilder object? (Choose two.)
A. When using versions of Java technology earlier than 5.0.
B. When sharing a StringBuffer among multiple threads.
C. When using the java.io class StringBufferInputStream.
D. When you plan to reuse the StringBuffer to build more than one string.
E. Enitiation of separate design processes to the separation of users
答案:AB
參考:11-2 文字類型
A. When using versions of Java technology earlier than 5.0.
B. When sharing a StringBuffer among multiple threads.
C. When using the java.io class StringBufferInputStream.
D. When you plan to reuse the StringBuffer to build more than one string.
E. Enitiation of separate design processes to the separation of users
答案:AB
參考:11-2 文字類型
第174題
Given
:
12. Date date = new Date();
13. df.setLocale(Locale.ITALY);
14. String s = df.format(date);
The variable df is an object of type DateFormat that has been initialized in line 11.
What is the result if this code is run on December 14, 2000?
A. The value of s is 14-dic-2000.
B. The value of s is Dec 14, 2000.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.
答案:D
參考:11-4 數字與日期/時間格式設定
:
12. Date date = new Date();
13. df.setLocale(Locale.ITALY);
14. String s = df.format(date);
The variable df is an object of type DateFormat that has been initialized in line 11.
What is the result if this code is run on December 14, 2000?
A. The value of s is 14-dic-2000.
B. The value of s is Dec 14, 2000.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.
答案:D
參考:11-4 數字與日期/時間格式設定
2009年2月19日 星期四
第173題
Given
:
11. public class Yikes{
12.
13. public static void go(Long n){System.out.print("Long ");}
14. public static void go(Short n){System. outprint("Short ");}
15. public static void go(int n){System.out.print("int ");}
16. public static void main(String[] args){
17. short y = 6;
18. long z = 7;
19. go(y);
20. go(z);
21. }
22. }
What is the result?
A. int Long
B. Short Long
C. Compilation fails.
D. An exception is thrown at runtime.
答案:A
參考:11-1 數字類型
----------------------------------
先找相同型態,再找尋可以自動轉型,最後找可以autoboxing的型態.
:
11. public class Yikes{
12.
13. public static void go(Long n){System.out.print("Long ");}
14. public static void go(Short n){System. outprint("Short ");}
15. public static void go(int n){System.out.print("int ");}
16. public static void main(String[] args){
17. short y = 6;
18. long z = 7;
19. go(y);
20. go(z);
21. }
22. }
What is the result?
A. int Long
B. Short Long
C. Compilation fails.
D. An exception is thrown at runtime.
答案:A
參考:11-1 數字類型
----------------------------------
先找相同型態,再找尋可以自動轉型,最後找可以autoboxing的型態.
第172題
Given
:
33. Date d = new Date(0);
34. String ds = "December 15, 2004";
35. //insert code here
36. try{
37. d = df.parse(ds);
38. }
39. catch(ParseException e){
40. System.out.println("Unable to parse " + ds);
41. }
42. //insert code here too
What creates the appropriate DateFormat object and adds a day to the Date object?
A. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setTime((60 * 60 * 24) + d.getTime();
B. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setTime((1000 * 60 * 60 * 24) + d.getTime());
C. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setLocalTime((1000 * 60 * 60 * 24) + d.getLocalTime());
D. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setLocalTime((60 * 60 * 24) + d.getLocalTime());
答案:B
參考:11-4 數字與日期/時間格式設定
--------------------------------------------------
先建立一個DateFormat物件, 因為ds內沒有時間, 所以用getDateInstance();
1000 * 60 * 60 * 24 (一天的時間).
:
33. Date d = new Date(0);
34. String ds = "December 15, 2004";
35. //insert code here
36. try{
37. d = df.parse(ds);
38. }
39. catch(ParseException e){
40. System.out.println("Unable to parse " + ds);
41. }
42. //insert code here too
What creates the appropriate DateFormat object and adds a day to the Date object?
A. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setTime((60 * 60 * 24) + d.getTime();
B. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setTime((1000 * 60 * 60 * 24) + d.getTime());
C. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setLocalTime((1000 * 60 * 60 * 24) + d.getLocalTime());
D. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setLocalTime((60 * 60 * 24) + d.getLocalTime());
答案:B
參考:11-4 數字與日期/時間格式設定
--------------------------------------------------
先建立一個DateFormat物件, 因為ds內沒有時間, 所以用getDateInstance();
1000 * 60 * 60 * 24 (一天的時間).
第171題
Given
:
11. String test = "a1b2c3";
12. String[] tokens = test.split("\\d");
13. for(String s : tokens) System.out.print(s + " ");
What is the result?
A. a b c
B. 1 2 3
C. a1b2c3
D. a1 b2 c3
E. Compilation fails.
F. The code runs with no output.
G. An exception is thrown at runtime.
答案:A
參考:11-5 規則運算式與相關類別
---------------------------------------
split 為分隔符號, \\d 代表數字, 所以跳過數字不看.
:
11. String test = "a1b2c3";
12. String[] tokens = test.split("\\d");
13. for(String s : tokens) System.out.print(s + " ");
What is the result?
A. a b c
B. 1 2 3
C. a1b2c3
D. a1 b2 c3
E. Compilation fails.
F. The code runs with no output.
G. An exception is thrown at runtime.
答案:A
參考:11-5 規則運算式與相關類別
---------------------------------------
split 為分隔符號, \\d 代表數字, 所以跳過數字不看.
第170題
Given
:
12. String csv = "Sue,5,true,3";
13. Scanner scanner = new Scanner(csv);
14. scanner.useDelimiter(",");
15. int age = scanner.nextInt(),
What is the result?
A. Compilation fails.
B. After line 15, the value of age is 5.
C. After line 15, the value of age is 3.
D. An exception is thrown at runtime.
答案:D
參考:11-5 規則運算式與相關類別
-----------------------------------------
15行 nextInt() 碰到文字就會產生 InputMissmatchException.
:
12. String csv = "Sue,5,true,3";
13. Scanner scanner = new Scanner(csv);
14. scanner.useDelimiter(",");
15. int age = scanner.nextInt(),
What is the result?
A. Compilation fails.
B. After line 15, the value of age is 5.
C. After line 15, the value of age is 3.
D. An exception is thrown at runtime.
答案:D
參考:11-5 規則運算式與相關類別
-----------------------------------------
15行 nextInt() 碰到文字就會產生 InputMissmatchException.
第169題
Given
:
12. NumberFormat nf = NumberFormat.getInstance();
13. nf.setMaximumFractionDigits(4);
14. nf.setMinimumFractionDigits(2);
15. String a = nf.format(3.1415926);
16. String b = nf.format(2);
Which two statements are true about The result if the default locale is Locale.US? (Choose two.)
A. The value of b is 2.
B. The value of a is 3.14.
C. The value of b is 2.00.
D. The value of a is 3.141.
E. The value of a is 3.1415.
F. The value of a is 3.1416.
G. The value of b is 2.0000.
答案:CF
參考:11-4 數字與日期/時間格式設定
---------------------------------------
setMaximumFractionDigits(4); //小數點到四位數,超過則四捨五入.
setMinimumFractionDigits(2); // 小數點最少取兩位.
:
12. NumberFormat nf = NumberFormat.getInstance();
13. nf.setMaximumFractionDigits(4);
14. nf.setMinimumFractionDigits(2);
15. String a = nf.format(3.1415926);
16. String b = nf.format(2);
Which two statements are true about The result if the default locale is Locale.US? (Choose two.)
A. The value of b is 2.
B. The value of a is 3.14.
C. The value of b is 2.00.
D. The value of a is 3.141.
E. The value of a is 3.1415.
F. The value of a is 3.1416.
G. The value of b is 2.0000.
答案:CF
參考:11-4 數字與日期/時間格式設定
---------------------------------------
setMaximumFractionDigits(4); //小數點到四位數,超過則四捨五入.
setMinimumFractionDigits(2); // 小數點最少取兩位.
第180題
Place the correct description of the compiler output on the code fragments to be inserted at lines 4 and 5. The
same compiler output may be used more than once.
1. import java.util.*;
2. public class X{
3. public static void main(String[] args){
4. //insert cede here
5. // insert code here
6. }
7. public static void foo(List<object> list){
8. } }
same compiler output may be used more than once.
1. import java.util.*;
2. public class X{
3. public static void main(String[] args){
4. //insert cede here
5. // insert code here
6. }
7. public static void foo(List<object> list){
8. } }
第178題
Given:
1. public class Target{
2. private int i = 0;
3. public int addOne(){
4. return ++i;
5. }
6. }
And:
1. public class Client{
2. public static void main(String[] args){
3. System.out.println(new Target().addOne());
4. }
5. }
Which change can you make to Target without affecting Client?
A. Line 4 of class Target can be changed to return i++;
B. Line 2 of class Target can be changed to private int i = 1;
C. Line 3 of class Target can be changed to private int addOne(){
D. Line 2 of class Target can be changed to private Integer i = 0;
答案:D
參考:11-1 數字類型
-------------------------------------------------------------------
更改Target類別的內容也不會更改結果
D. Line 2 of class Target can be changed to private Integer i = 0; //會autoynboxing
1. public class Target{
2. private int i = 0;
3. public int addOne(){
4. return ++i;
5. }
6. }
And:
1. public class Client{
2. public static void main(String[] args){
3. System.out.println(new Target().addOne());
4. }
5. }
Which change can you make to Target without affecting Client?
A. Line 4 of class Target can be changed to return i++;
B. Line 2 of class Target can be changed to private int i = 1;
C. Line 3 of class Target can be changed to private int addOne(){
D. Line 2 of class Target can be changed to private Integer i = 0;
答案:D
參考:11-1 數字類型
-------------------------------------------------------------------
更改Target類別的內容也不會更改結果
D. Line 2 of class Target can be changed to private Integer i = 0; //會autoynboxing
第177題
Given:
11. String test = "This is a test";
12. String[] tokens = test.split("\s");
13. System.out.println(tokens.length);
What is the result?
A. 0
B. 1
C. 4
D. Compilation fails.
E. An exception is thrown at runtime.
答案:D
參考:11-5 規則運算式與相關類別
11. String test = "This is a test";
12. String[] tokens = test.split("\s");
13. System.out.println(tokens.length);
What is the result?
A. 0
B. 1
C. 4
D. Compilation fails.
E. An exception is thrown at runtime.
答案:D
參考:11-5 規則運算式與相關類別
第176題
Place the code fragments into position to produce the output: true true false
Code
Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);
scanner.useDelimiter(",");
while( Place hete ){
if( Place hete ){
System.out.print( Place hete + " ");
}else Place hete ;
}
Code Fragments
scanner.hasNextBoolean()
scanner.nextBoolean()
scanner.next()
scanner.hasNext()
答案:
Code
Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);
scanner.useDelimiter(",");
while( scanner.hasNext() ){
if( scanner.hasNextBoolean() ){
System.out.print( scanner.nextBoolean() + " ");
}else scanner.next() ;
}
參考:11-5-2 Scanner類別
Code
Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);
scanner.useDelimiter(",");
while( Place hete ){
if( Place hete ){
System.out.print( Place hete + " ");
}else Place hete ;
}
Code Fragments
scanner.hasNextBoolean()
scanner.nextBoolean()
scanner.next()
scanner.hasNext()
答案:
Code
Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);
scanner.useDelimiter(",");
while( scanner.hasNext() ){
if( scanner.hasNextBoolean() ){
System.out.print( scanner.nextBoolean() + " ");
}else scanner.next() ;
}
參考:11-5-2 Scanner類別
第168題
Given:
11. public void testIfA(){
12. if(testIfB("True")){
13. System.out.println("True");
14. }else{
15. System.out.println("Not true");
16. }
17. }
18. public Boolean testIfB(String str){
19. return Boolean.valueOf(str);
20. }
What is the result when method testIfA is invoked?
A. True
B. Not true
C. An exception is thrown at runtime.
D. Compilation fails because of an error at line 12.
E. Compilation fails because of an error at line 19.
答案:A
參考:11-1-2 Wrapper類別
-------------------------------------------------------
12. if(testIfB("True")){
>> 18. public Boolean testIfB(String str){
>> 19. return Boolean.valueOf(str); //把字串"True"變Boolean的True
11. public void testIfA(){
12. if(testIfB("True")){
13. System.out.println("True");
14. }else{
15. System.out.println("Not true");
16. }
17. }
18. public Boolean testIfB(String str){
19. return Boolean.valueOf(str);
20. }
What is the result when method testIfA is invoked?
A. True
B. Not true
C. An exception is thrown at runtime.
D. Compilation fails because of an error at line 12.
E. Compilation fails because of an error at line 19.
答案:A
參考:11-1-2 Wrapper類別
-------------------------------------------------------
12. if(testIfB("True")){
>> 18. public Boolean testIfB(String str){
>> 19. return Boolean.valueOf(str); //把字串"True"變Boolean的True
第167題
Given:
11. String test = "Test A. Test B. Test C.";
12. //insert code here
13. String[] result = test.split(regex);
Which regular expression, inserted at line 12, correctly splits test into "Test A",
"Test B", and "Test C"?
A. String regex = "";
B. String regex = " ";
C. String regex = ".*";
D. String regex = "\\s";
E. String regex = "\\.\\s*";
F. String regex = "\\w[\.] +";
答案:E
參考:11-5 規則運算式與相關類別
-----------------------------------------------------------
第12行插入code而原字串變成"Test A", "Test B", and "Test C"
E. String regex = "\\.\\s*"; // \\.=小數點,\\s*=空白
11. String test = "Test A. Test B. Test C.";
12. //insert code here
13. String[] result = test.split(regex);
Which regular expression, inserted at line 12, correctly splits test into "Test A",
"Test B", and "Test C"?
A. String regex = "";
B. String regex = " ";
C. String regex = ".*";
D. String regex = "\\s";
E. String regex = "\\.\\s*";
F. String regex = "\\w[\.] +";
答案:E
參考:11-5 規則運算式與相關類別
-----------------------------------------------------------
第12行插入code而原字串變成"Test A", "Test B", and "Test C"
E. String regex = "\\.\\s*"; // \\.=小數點,\\s*=空白
第166題
Given:
1. public class BuildStuff{
2. public static void main(String[] args){
3. Boolean test = new Boolean(true);
4. Integer x = 343;
5. Integer y = new BuildStuff().go(test, x);
6. System.out.println(y);
7. }
8. int go(Boolean b, int i){
9. if(b) return (i/7);
10. return (i/49);
11. }
12. }
What is the result?
A. 7
B. 49
C. 343
D. Compilation fails.
E. An exception is thrown at runtime.
答案:B
參考:11-1 數字類型
-----------------------------------------------
3. Boolean test = new Boolean(true); //test =true
5. Integer y = new BuildStuff().go(test, x); //x=343
9. if(b) return (i/7); //b=true...343/7=49
1. public class BuildStuff{
2. public static void main(String[] args){
3. Boolean test = new Boolean(true);
4. Integer x = 343;
5. Integer y = new BuildStuff().go(test, x);
6. System.out.println(y);
7. }
8. int go(Boolean b, int i){
9. if(b) return (i/7);
10. return (i/49);
11. }
12. }
What is the result?
A. 7
B. 49
C. 343
D. Compilation fails.
E. An exception is thrown at runtime.
答案:B
參考:11-1 數字類型
-----------------------------------------------
3. Boolean test = new Boolean(true); //test =true
5. Integer y = new BuildStuff().go(test, x); //x=343
9. if(b) return (i/7); //b=true...343/7=49
第165題
Given:
5. import java.util.Date;
6. import java.text.DateFormat;
21. DateFormat df;
22. Date date = new Date();
23. //insert code here
24. String s = df.format(date);
Which code fragment, inserted at line 23, allows the code to compile?
A. df = new DateFormat();
B. df = Date.getFormat();
C. df = date.getFormat();
D. df = DateFormat.getFormat();
E. df = DateFormat.getInstance();
答案:E
參考:11-4 數字與日期/時間格式設定
--------------------------------------------------------------------
第23行要插入code讓程式compile成功
E. df = DateFormat.getInstance(); //會取得DateFormat的物件實體
5. import java.util.Date;
6. import java.text.DateFormat;
21. DateFormat df;
22. Date date = new Date();
23. //insert code here
24. String s = df.format(date);
Which code fragment, inserted at line 23, allows the code to compile?
A. df = new DateFormat();
B. df = Date.getFormat();
C. df = date.getFormat();
D. df = DateFormat.getFormat();
E. df = DateFormat.getInstance();
答案:E
參考:11-4 數字與日期/時間格式設定
--------------------------------------------------------------------
第23行要插入code讓程式compile成功
E. df = DateFormat.getInstance(); //會取得DateFormat的物件實體
第164題
Given:
1. d is a valid, non-null Date object
2. df is a valid, non-null DateFormat object set to the current locale
What outputs the current locale's country name and the appropriate version of d's date?
A. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));
B. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));
C. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
D. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
答案:B
參考:11-4 數字與日期/時間格式設定
1. d is a valid, non-null Date object
2. df is a valid, non-null DateFormat object set to the current locale
What outputs the current locale's country name and the appropriate version of d's date?
A. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));
B. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));
C. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
D. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
答案:B
參考:11-4 數字與日期/時間格式設定
第163題
Given:
1. public class TestString3{
2. public static void main(String[] args){
3. //insert code here
5. System.out.println(s);
6. }
7. }
Which two code fragments, inserted independently at line 3, generate the output 4247? (choose two.)
A. String s = "123456789";
s = (s - "123").replace(1, 3, "24") - "89";
B. StringBuffer s = new StringBuffer("123456789");
s.delete(0, 3).replace(1, 3, "24").delete(4, 6);
C. StringBuffer s = new StringBuffer("123456789");
s.substring(3, 6).delete(1, 3).insert(1, "24");
D. StringBuilder s = new StringBuilder("123456789");
s.substring(3, 6).delete(1, 2).insert(1, "24");
E. StringBuilder s = new StringBuilder("123456789");
s.delete(0, 3).delete(1, 3).delete(2, 5).insert(1, "24");
答案:BE
參考:11-2 文字類型
----------------------------------------------------------
A. 字串不能用減號
C. 字串沒有delete
D. 字串沒有delete
1. public class TestString3{
2. public static void main(String[] args){
3. //insert code here
5. System.out.println(s);
6. }
7. }
Which two code fragments, inserted independently at line 3, generate the output 4247? (choose two.)
A. String s = "123456789";
s = (s - "123").replace(1, 3, "24") - "89";
B. StringBuffer s = new StringBuffer("123456789");
s.delete(0, 3).replace(1, 3, "24").delete(4, 6);
C. StringBuffer s = new StringBuffer("123456789");
s.substring(3, 6).delete(1, 3).insert(1, "24");
D. StringBuilder s = new StringBuilder("123456789");
s.substring(3, 6).delete(1, 2).insert(1, "24");
E. StringBuilder s = new StringBuilder("123456789");
s.delete(0, 3).delete(1, 3).delete(2, 5).insert(1, "24");
答案:BE
參考:11-2 文字類型
----------------------------------------------------------
A. 字串不能用減號
C. 字串沒有delete
D. 字串沒有delete
第162題
Given:
11. public static void main(String[] args){
12. Integer i = new Integer(1) + new Integer(2);
13. switch(i){
14. case 3: System.out.println("three"); break;
15. default: System.out.println("other"); break;
16. }
17. }
What is the result?
A. three
B. other
C. An exception is thrown at runtime.
D. Compilation fails because of an error on line 12.
E. Compilation fails because of an error on line 13.
F. Compilation fails because of an error on line 15.
答案:A
參考:11-1 數字類型
-----------------------------------------------------
12. Integer i = new Integer(1) + new Integer(2); //i=3
11. public static void main(String[] args){
12. Integer i = new Integer(1) + new Integer(2);
13. switch(i){
14. case 3: System.out.println("three"); break;
15. default: System.out.println("other"); break;
16. }
17. }
What is the result?
A. three
B. other
C. An exception is thrown at runtime.
D. Compilation fails because of an error on line 12.
E. Compilation fails because of an error on line 13.
F. Compilation fails because of an error on line 15.
答案:A
參考:11-1 數字類型
-----------------------------------------------------
12. Integer i = new Integer(1) + new Integer(2); //i=3
2009年2月18日 星期三
JDK 版本名稱
Version | Date | CodeName | 中文名稱 |
JDK 1.0 | (January 23, 1996) | Oak. | 橡樹 |
JDK 1.1 | (February 19, 1997) | ||
J2SE 1.2 | (December 8, 1998) | Playground | 遊樂場 |
J2SE 1.3 | (May 8, 2000) | Kestrel | 茶隼 |
J2SE 1.4 | (February 6, 2002) | Merlin | 隼 |
J2SE 5.0 | (September 30, 2004) | Tiger | 虎 |
Java SE 6 | (December 11, 2006) | Mustang | 野馬 |
Java SE 7 | recent | Dolphin | 海豚 |
第161題
Given:
1. public class Boxer1{
2. Integer i
3. int x;
4. public Boxer1(int y){
5. x = i + y;
6. System.out.println(x);
7. }
8. public static void main(String[] args){
9. new Boxer1(new Integer(4));
10. }
11. }
What is the result?
A. The value "4" is printed at the command line.
B. Compilation fails because of an error in line 5.
C. Compilation fails because of an error in line 9.
D. A NullPointerException occurs at runtime.
E. A NumberFormatException occurs at runtime.
F. An IllegalStateException occurs at runtime.
答案:D
參考:11-1 數字類型
------------------------------------
Integer i 沒有給初始值, 所以初始值是 null, null 跟 數字相機阿就產生 NullPointerException
1. public class Boxer1{
2. Integer i
3. int x;
4. public Boxer1(int y){
5. x = i + y;
6. System.out.println(x);
7. }
8. public static void main(String[] args){
9. new Boxer1(new Integer(4));
10. }
11. }
What is the result?
A. The value "4" is printed at the command line.
B. Compilation fails because of an error in line 5.
C. Compilation fails because of an error in line 9.
D. A NullPointerException occurs at runtime.
E. A NumberFormatException occurs at runtime.
F. An IllegalStateException occurs at runtime.
答案:D
參考:11-1 數字類型
------------------------------------
Integer i 沒有給初始值, 所以初始值是 null, null 跟 數字相機阿就產生 NullPointerException
第160題
Given:
22. StringBuilder sb1 = new StringBuilder("123");
23. String s1 = "123";
24. //insert code here
25. System.out.println(sb1 + " " + s1);
Which code fragment, inserted at line 24, outputs "123abc 123abc"?
A. sb1.append("abc"); s1.append("abc");
B. sb1.append("abc"); s1.concat("abc");
C. sb1.concat("abc"); s1.append("abc");
D. sb1.concat("abc"); s1.concat("abc");
E. sb1.append("abc"); s1 = s1.concat("abc");
F. sb1.concat("abc"); s1 = s1.concat("abc");
G. sb1.append("abc"); s1 = s1 + s1.concat("abc");
H. sb1.concat("abc"); s1 = s1 + s1.concat("abc");
答案:E
參考:11-2 文字類型
----------------------------------------
sb1.append("abc"); //原來的字串後面插入abc , 123abc
s1 = s1.concat("abc"); //concat() 會做串接, 並產生一個新的實體. 所以要在指定回給s1.
22. StringBuilder sb1 = new StringBuilder("123");
23. String s1 = "123";
24. //insert code here
25. System.out.println(sb1 + " " + s1);
Which code fragment, inserted at line 24, outputs "123abc 123abc"?
A. sb1.append("abc"); s1.append("abc");
B. sb1.append("abc"); s1.concat("abc");
C. sb1.concat("abc"); s1.append("abc");
D. sb1.concat("abc"); s1.concat("abc");
E. sb1.append("abc"); s1 = s1.concat("abc");
F. sb1.concat("abc"); s1 = s1.concat("abc");
G. sb1.append("abc"); s1 = s1 + s1.concat("abc");
H. sb1.concat("abc"); s1 = s1 + s1.concat("abc");
答案:E
參考:11-2 文字類型
----------------------------------------
sb1.append("abc"); //原來的字串後面插入abc , 123abc
s1 = s1.concat("abc"); //concat() 會做串接, 並產生一個新的實體. 所以要在指定回給s1.
第159題
Given:
11. double input = 314159.26;
12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
13. String b;
14. //insert code here
Which code, inserted at line 14, sets the value of b to 314.159,26?
A. b = nf.parse(input);
B. b = nf.format(input);
C. b = nf.equals(input);
D. b = nf.parseObject(input);
答案:B
參考:11-4-1 NumberFormat類別
--------------------------------------------------------------
314.159,26 在義大利文裡,小數點是千分符號, 逗點是小數點, 跟一般常用相反.
nf取得ITALIAN格式後在 格式化.
11. double input = 314159.26;
12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
13. String b;
14. //insert code here
Which code, inserted at line 14, sets the value of b to 314.159,26?
A. b = nf.parse(input);
B. b = nf.format(input);
C. b = nf.equals(input);
D. b = nf.parseObject(input);
答案:B
參考:11-4-1 NumberFormat類別
--------------------------------------------------------------
314.159,26 在義大利文裡,小數點是千分符號, 逗點是小數點, 跟一般常用相反.
nf取得ITALIAN格式後在 格式化.
第158題
Given a vaid DateFormat object named df, and
16. Date d = new Date(0L);
17. String ds = "December 15, 2004";
18. //insert code here
What updates d's value with the date represented by ds?
A. 18. d = df.parse(ds);
B. 18. d = df.getDate(ds);
C. 18. try{
19. d = df.parse(ds);
20. }catch(ParseException e){}
D. 18. try{
19. d = df.getDate(ds);
20. }catch(ParseException e){}
答案:C
參考:11-4 數字與日期/時間格式設定
----------------------------------------
解析第17行 變成 Date, 並用ParseException 去接可能發生的例外.
16. Date d = new Date(0L);
17. String ds = "December 15, 2004";
18. //insert code here
What updates d's value with the date represented by ds?
A. 18. d = df.parse(ds);
B. 18. d = df.getDate(ds);
C. 18. try{
19. d = df.parse(ds);
20. }catch(ParseException e){}
D. 18. try{
19. d = df.getDate(ds);
20. }catch(ParseException e){}
答案:C
參考:11-4 數字與日期/時間格式設定
----------------------------------------
解析第17行 變成 Date, 並用ParseException 去接可能發生的例外.
第157題
Given that c is a reference to a valid java.io.Console object, and:
11. String pw = c.readPassword("%s", "pw: ");
12. System.out.println("got " + pw);
13. String name = c.readLine("%s", "name: ");
14. System.out.println(" got", name);
If the user types fido when prompted for a password, and then responds bob when prompted for a name, what is the result?
A. pw:
got fido
name: bob
got bob
B. pw: fido
got fido
name: bob
got bob
C. pw:
got fido
name: bob got bob
D. pw: fido
got lido
name: bob got bob
E. Compilation fails.
F. An exception is thrown at runtime.
答案:E
參考:10-2 Console類別
------------------------------------
11. String pw = c.readPassword("%s", "pw: "); //回傳字元陣列, 而不是字串
11. String pw = c.readPassword("%s", "pw: ");
12. System.out.println("got " + pw);
13. String name = c.readLine("%s", "name: ");
14. System.out.println(" got", name);
If the user types fido when prompted for a password, and then responds bob when prompted for a name, what is the result?
A. pw:
got fido
name: bob
got bob
B. pw: fido
got fido
name: bob
got bob
C. pw:
got fido
name: bob got bob
D. pw: fido
got lido
name: bob got bob
E. Compilation fails.
F. An exception is thrown at runtime.
答案:E
參考:10-2 Console類別
------------------------------------
11. String pw = c.readPassword("%s", "pw: "); //回傳字元陣列, 而不是字串
第156題
Place the code fragments into position to use a BufferedReader to read in an entire text file.
class PrintFile{
public static void main(String[] args){
BufferedReader buffReader = null; /
//More code here to initialize buffReader
try{
String temp;
while( Place here Place here ){
System.out.println(temp);
}
}catch Place here
e.printStackTrace();
}
}
}
Code Fragments
(temp = buffReader.readLine())
&& buffReader.hasNext()
(temp = buffReader.nextLine())
(IOException e){
!= null
(FileNotFoundException e){
答案:
class PrintFile{
public static void main(String[] args){
BufferedReader buffReader = null; /
//More code here to initialize buffReader
try{
String temp;
while( (temp = buffReader.readLine()) != null ){
System.out.println(temp);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
參考:10-5-1 BufferedReader與BufferedWriter類別
------------------------------------
BufferedReader 是屬於 IO
class PrintFile{
public static void main(String[] args){
BufferedReader buffReader = null; /
//More code here to initialize buffReader
try{
String temp;
while( Place here Place here ){
System.out.println(temp);
}
}catch Place here
e.printStackTrace();
}
}
}
Code Fragments
(temp = buffReader.readLine())
&& buffReader.hasNext()
(temp = buffReader.nextLine())
(IOException e){
!= null
(FileNotFoundException e){
答案:
class PrintFile{
public static void main(String[] args){
BufferedReader buffReader = null; /
//More code here to initialize buffReader
try{
String temp;
while( (temp = buffReader.readLine()) != null ){
System.out.println(temp);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
參考:10-5-1 BufferedReader與BufferedWriter類別
------------------------------------
BufferedReader 是屬於 IO
第155題
The doesFileExist method takes an array of directory names representing a path from the root filesystem and a file name. The method returns true if the file exists, false if it does not.
Place the code fragments in position to complete this method.
public static boolean doesFileExist(String[] directories, String filename){
Place here
for(String dir : directories){
Place here
}
Place here
Place here
}
Code Fragments
path = path.getSubdirectory(dir);
return !file.isNew();
return(file != null);
String path = "";
path = path.getFile(filename);
File path = new File("");
return file.exists();
return path.isFile();
File file = new File(path, filename);
path = new File(path, dir);
File path = new File(File.separator);
path = path + File.separator + dir;
答案:
public static boolean doesFileExist(String[] directories, String filename){
String path = "";
for(String dir : directories){
path = path + File.separator + dir;
}
File file = new File(path, filename);
return file.exists();
}
參考:10-3 File類別
Place the code fragments in position to complete this method.
public static boolean doesFileExist(String[] directories, String filename){
Place here
for(String dir : directories){
Place here
}
Place here
Place here
}
Code Fragments
path = path.getSubdirectory(dir);
return !file.isNew();
return(file != null);
String path = "";
path = path.getFile(filename);
File path = new File("");
return file.exists();
return path.isFile();
File file = new File(path, filename);
path = new File(path, dir);
File path = new File(File.separator);
path = path + File.separator + dir;
答案:
public static boolean doesFileExist(String[] directories, String filename){
String path = "";
for(String dir : directories){
path = path + File.separator + dir;
}
File file = new File(path, filename);
return file.exists();
}
參考:10-3 File類別
2009年2月17日 星期二
第147題
Given:
1. public class LineUp{
2. public static void main(String[] args){
3. double d = 12.345;
4. //insert code here
5. }
6. }
Which code fragment, inserted at line 4, produces the output 12.345?
A. System.out.printf("%7d \n", d);
B. System.out.printf("%7f \n", d);
C. System.out.printf("%3.7d \n", d);
D. System.out.printf("%3.7f \n", d);
E. System.out.printf("%7.3d \n", d);
F. System.out.printf("%7.3f \n", d);
答案:F
參考:10-2 Console類別
-------------------------------------
System.out.printf("%7.3f \n", d);
// 7 = 寬度
// .3 = 小數點後幾碼
// f = 類型 float.
1. public class LineUp{
2. public static void main(String[] args){
3. double d = 12.345;
4. //insert code here
5. }
6. }
Which code fragment, inserted at line 4, produces the output 12.345?
A. System.out.printf("%7d \n", d);
B. System.out.printf("%7f \n", d);
C. System.out.printf("%3.7d \n", d);
D. System.out.printf("%3.7f \n", d);
E. System.out.printf("%7.3d \n", d);
F. System.out.printf("%7.3f \n", d);
答案:F
參考:10-2 Console類別
-------------------------------------
System.out.printf("%7.3f \n", d);
// 7 = 寬度
// .3 = 小數點後幾碼
// f = 類型 float.
第146題
Given:
1. import java.io.*;
2. public class Foo implements Serializable{
3. public int x, y;
4. public Foo(int x, int y){this.x = x; this.y = y;}
5.
6. private void writeObject(ObjctOutputStream s)
7. throws IOException{
8. s.writeInt(x); s.writeInt(y);
9. }
10.
11. private void readObject(ObjectInputStream s)
12. throws IOException, ClassNotFoundException{
13.
14. //insert code here
15.
16. }
17. }
Which code, inserted at line 14, will allow this class to correctly serialize and deserialize?
A. s.defaultReadObject();
B. this = s.defaultReadObject(),
C. y = s.readInt(); x = s.readInt();
D. x = s.readInt(); y = s.readInt();
答案:D
參考:10-5 多重串接
-----------------------------------------
writeObject 是專門序列化的方法, 裡面先寫入
s.writeInt(x); s.writeInt(y);
readObject 反序列化就是把他讀取出來.
所以x = s.readInt(); y = s.readInt();
1. import java.io.*;
2. public class Foo implements Serializable{
3. public int x, y;
4. public Foo(int x, int y){this.x = x; this.y = y;}
5.
6. private void writeObject(ObjctOutputStream s)
7. throws IOException{
8. s.writeInt(x); s.writeInt(y);
9. }
10.
11. private void readObject(ObjectInputStream s)
12. throws IOException, ClassNotFoundException{
13.
14. //insert code here
15.
16. }
17. }
Which code, inserted at line 14, will allow this class to correctly serialize and deserialize?
A. s.defaultReadObject();
B. this = s.defaultReadObject(),
C. y = s.readInt(); x = s.readInt();
D. x = s.readInt(); y = s.readInt();
答案:D
參考:10-5 多重串接
-----------------------------------------
writeObject 是專門序列化的方法, 裡面先寫入
s.writeInt(x); s.writeInt(y);
readObject 反序列化就是把他讀取出來.
所以x = s.readInt(); y = s.readInt();
第145題
Given that the current directory is empty, and that the user has read and write permissions, and the following:
11. import java.io.*;
12. public class DOS{
13. public static void main(String[] args){
14. File dir = new File("dir");
15. dir.mkdir();
16. File f1 = new File(dir, "f1.txt");
17. try{
18. f1.createNewFile();
19. }catch(IOException e){;}
20. File newDir = new File("newDir");
21. dir.renameTo(newDir);
22. }
23. }
Which statement is true?
A. Compilation fails.
B. The file system has a new empty directory named dir.
C. The file system has a new empty directory named newDir.
D. The file system has a directory named dir, containing a file f1.txt.
E. The file system has a directory named newDir, containing a file f1.txt.
答案:E
參考:10-3 File類別
------------------------------------------
14. File dir = new File("dir"); //命名一個檔名為dir
15. dir.mkdir(); // 用此名建立一個目錄
16. File f1 = new File(dir, "f1.txt"); // 在dir 下面開一個 f1.txt
18. f1.createNewFile(); // 建立檔案.
20. File newDir = new File("newDir"); //命名一個檔名為 newDir
21. dir.renameTo(newDir); //把原來的 dir 改成 newDir.
11. import java.io.*;
12. public class DOS{
13. public static void main(String[] args){
14. File dir = new File("dir");
15. dir.mkdir();
16. File f1 = new File(dir, "f1.txt");
17. try{
18. f1.createNewFile();
19. }catch(IOException e){;}
20. File newDir = new File("newDir");
21. dir.renameTo(newDir);
22. }
23. }
Which statement is true?
A. Compilation fails.
B. The file system has a new empty directory named dir.
C. The file system has a new empty directory named newDir.
D. The file system has a directory named dir, containing a file f1.txt.
E. The file system has a directory named newDir, containing a file f1.txt.
答案:E
參考:10-3 File類別
------------------------------------------
14. File dir = new File("dir"); //命名一個檔名為dir
15. dir.mkdir(); // 用此名建立一個目錄
16. File f1 = new File(dir, "f1.txt"); // 在dir 下面開一個 f1.txt
18. f1.createNewFile(); // 建立檔案.
20. File newDir = new File("newDir"); //命名一個檔名為 newDir
21. dir.renameTo(newDir); //把原來的 dir 改成 newDir.
第144題
Which capability exists only in java.io.BufferedWriter?
A. Closing an open stream.
B. Flushing an open stream.
C. Writing to an open stream.
D. Writing a line separator to an open stream.
答案:D
參考:10-5 多重串接
--------------------------------------
什麼樣的能力只存在於BufferedWriter裡面,
可以換行 (new line) /n
A. Closing an open stream.
B. Flushing an open stream.
C. Writing to an open stream.
D. Writing a line separator to an open stream.
答案:D
參考:10-5 多重串接
--------------------------------------
什麼樣的能力只存在於BufferedWriter裡面,
可以換行 (new line) /n
第143題
Given:
System.out.printf("Pi is approximately %f and E is approximately %b, Math.PI, Math.E);
Place the values where they would appear in the output.
System.out.printf("Pi is approximately %f and E is approximately %b, Math.PI, Math.E);
Place the values where they would appear in the output.
答案:
Pi is approximately 3.141593
and E is approximately true
參考:10-2 Console類別、11-1 數字類型
----------------------------------------
%f 格式化 Math.PI , float
%b 格式化 Math.E , 除非是布林值的 false, 不然就是true.
第142題
Assuming that the serializeBanana() and the deserializeBanana() methods will correctly use Java serialization and given:
13. import java.io.*;
14. class Food implements Serializable{int good = 3;}
15. class Fruit extends Food{int juice = 5;}
16. public class Banana extends Fruit{
17. int yellow = 4;
18. public static void main(String[] args) {
19. Banana b = new Banana(); Banana b2 = new Banana();
20. b.serializeBanana(b); //assume correct serialization
21. b2 = b.deserializeBanana(); //assume correct
22. System.out.println("restore " + b2.yellow + b2.juice + b2.good);
24. }
25. //more Banana methods go here
50. }
What is the result?
A. restore 400
B. restore 403
C. restore 453
D. Compilation fails.
E. An exception is thrown at runtime.
答案:C
參考:10-5 多重串接
-------------------------------------
20. b.serializeBanana(b); // 序列化b
21. b2 = b.deserializeBanana(); //反序列化 b 給 b2, 此時 b2 的實體跟b 一樣.
13. import java.io.*;
14. class Food implements Serializable{int good = 3;}
15. class Fruit extends Food{int juice = 5;}
16. public class Banana extends Fruit{
17. int yellow = 4;
18. public static void main(String[] args) {
19. Banana b = new Banana(); Banana b2 = new Banana();
20. b.serializeBanana(b); //assume correct serialization
21. b2 = b.deserializeBanana(); //assume correct
22. System.out.println("restore " + b2.yellow + b2.juice + b2.good);
24. }
25. //more Banana methods go here
50. }
What is the result?
A. restore 400
B. restore 403
C. restore 453
D. Compilation fails.
E. An exception is thrown at runtime.
答案:C
參考:10-5 多重串接
-------------------------------------
20. b.serializeBanana(b); // 序列化b
21. b2 = b.deserializeBanana(); //反序列化 b 給 b2, 此時 b2 的實體跟b 一樣.
第141題
Given:
11. class A{
12. public void process(){System.out.print("A, ");}
13. class B extends A{
14. public void process() throws IOException{
15. super.process();
16. System.out.print("B, ");
17. throw new IOException(),
18. }
19. public static void main(String[] args){
20. try{new B().process();}
21. catch(IOException e){System.out.println("Exception");}
22. }
What is the result?
A. Exception
B. A, B, Exception
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 14.
E. A NullPointerException is thrown at runtime.
答案:D
參考:9-2 Java例外事件與處理機制、9-3 使用throw自行產生例外事件、9-5 使用throws拋出例外事件。
-----------------------------------
14行 子類別B 裡的process 要改寫 父類別A的 process, 但 父類別的 process 並沒有 throws IOException
11. class A{
12. public void process(){System.out.print("A, ");}
13. class B extends A{
14. public void process() throws IOException{
15. super.process();
16. System.out.print("B, ");
17. throw new IOException(),
18. }
19. public static void main(String[] args){
20. try{new B().process();}
21. catch(IOException e){System.out.println("Exception");}
22. }
What is the result?
A. Exception
B. A, B, Exception
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 14.
E. A NullPointerException is thrown at runtime.
答案:D
參考:9-2 Java例外事件與處理機制、9-3 使用throw自行產生例外事件、9-5 使用throws拋出例外事件。
-----------------------------------
14行 子類別B 裡的process 要改寫 父類別A的 process, 但 父類別的 process 並沒有 throws IOException
第133題
Given:
10. public class ClassA{
11. public void methodA(){
12. ClassB classB = new ClassB();
13. classB.getValue();
14. }
15. }
And:
20. class ClassB{
21. public ClassC classC;
22.
23. public String getValue(){
24. return classC.getValue();
25. }
26. }
And:
30. class ClassC{
31. public String value;
32.
33. public String getValue(){
34. value = "ClassB";
35. return value;
36. }
37. }
And given:
ClassA a = new ClassA();
a.methodA();
What is the result?
A. Compilation fails.
B. ClassC is displayed.
C. The code runs with no output.
D. An exception is thrown at runtime
答案:D
參考:9-2 Java例外事件與處理機制
------------------------------------
ClassA a = new ClassA();
並呼叫 a.mthodA();
>>12. ClassB classB = new ClassB();
>>13. classB.getValue();
>>>23. public String getValue(){
>>>24. return classC.getValue(); //此時產稱 NullPointerException,
原因21. public ClassC classC; 沒有實體化,預設初始值是null;
10. public class ClassA{
11. public void methodA(){
12. ClassB classB = new ClassB();
13. classB.getValue();
14. }
15. }
And:
20. class ClassB{
21. public ClassC classC;
22.
23. public String getValue(){
24. return classC.getValue();
25. }
26. }
And:
30. class ClassC{
31. public String value;
32.
33. public String getValue(){
34. value = "ClassB";
35. return value;
36. }
37. }
And given:
ClassA a = new ClassA();
a.methodA();
What is the result?
A. Compilation fails.
B. ClassC is displayed.
C. The code runs with no output.
D. An exception is thrown at runtime
答案:D
參考:9-2 Java例外事件與處理機制
------------------------------------
ClassA a = new ClassA();
並呼叫 a.mthodA();
>>12. ClassB classB = new ClassB();
>>13. classB.getValue();
>>>23. public String getValue(){
>>>24. return classC.getValue(); //此時產稱 NullPointerException,
原因21. public ClassC classC; 沒有實體化,預設初始值是null;
第132題
Given:
1. class TestException extends Exception{}
2. class A{
3. public String sayHello(String name) throws TestException{
4. if(name == null) throw new TestException(),
5. return "Hello " + name;
6. }
7. }
8. public class TestA{
9. public static void main(String[] args){
10. new A().sayHello("Aiko");
11. }
12. }
Which statement is true?
A. Compilation succeeds.
B. class A does not compile.
C. The method declared on line 9 cannot be modified to throw TestException.
D. TestA compiles if line 10 is enclosed in try/catch block that catches TestException.
答案:D
參考:9-2 Java例外事件與處理機制、9-3 使用throw自行產生例外事件、9-4 自訂例外類別、9-5 使用throws拋出例外事件。
-----------------------------
11行呼叫了 SayHello(), 並SayHello() 說明了可能會拋出TestException, TestException 是 Exception 子類別, 所拋出的exception由第10行處理, 所以第10行必須有try / catch 或是 手動 throw Exception.
1. class TestException extends Exception{}
2. class A{
3. public String sayHello(String name) throws TestException{
4. if(name == null) throw new TestException(),
5. return "Hello " + name;
6. }
7. }
8. public class TestA{
9. public static void main(String[] args){
10. new A().sayHello("Aiko");
11. }
12. }
Which statement is true?
A. Compilation succeeds.
B. class A does not compile.
C. The method declared on line 9 cannot be modified to throw TestException.
D. TestA compiles if line 10 is enclosed in try/catch block that catches TestException.
答案:D
參考:9-2 Java例外事件與處理機制、9-3 使用throw自行產生例外事件、9-4 自訂例外類別、9-5 使用throws拋出例外事件。
-----------------------------
11行呼叫了 SayHello(), 並SayHello() 說明了可能會拋出TestException, TestException 是 Exception 子類別, 所拋出的exception由第10行處理, 所以第10行必須有try / catch 或是 手動 throw Exception.
第154題
Given that c is a reference to a valid java.io.Console object, which two code fragments read a line of text
from the console? (Choose two.)
A. String s = c.readLine();
B. char[] c = c.readLine();
C. String s = c.readConsole();
D. char[] c = c.readConsole();
E. String s = c.readLine("%s", "name ");
F. char[] c = c.readLine("%s", "name ");
答案:AE
參考:10-2 Console類別
-------------------------------------------------------------------------------------------------
從主控台的模式下讀取一列資料
String s = c.readLine...
from the console? (Choose two.)
A. String s = c.readLine();
B. char[] c = c.readLine();
C. String s = c.readConsole();
D. char[] c = c.readConsole();
E. String s = c.readLine("%s", "name ");
F. char[] c = c.readLine("%s", "name ");
答案:AE
參考:10-2 Console類別
-------------------------------------------------------------------------------------------------
從主控台的模式下讀取一列資料
String s = c.readLine...
第153題
Chain these constructors to create objects to read from a file named "in" and to write to a file named "out".
reader = Place here Place here "in" ));
writer = Place here Place here Place here "out" )));
Constructors
new FileReader(
new PrintReader(
new BufferedReader(
new BufferedWriter(
new FileWriter(
new PrintWriter(
答案:
reader = new BufferedReader( new FileReader( "in" ));
writer = new PrintWriter( new BufferedWriter( new FileWriter( "out" )));
參考:10-5-1 BufferedReader與BufferedWriter類別
reader = Place here Place here "in" ));
writer = Place here Place here Place here "out" )));
Constructors
new FileReader(
new PrintReader(
new BufferedReader(
new BufferedWriter(
new FileWriter(
new PrintWriter(
答案:
reader = new BufferedReader( new FileReader( "in" ));
writer = new PrintWriter( new BufferedWriter( new FileWriter( "out" )));
參考:10-5-1 BufferedReader與BufferedWriter類別
第152題
Which three statements concerning the use of the java.io.Serializable interface are true? (Choose three.)
A. Objects from classes that use aggregation cannot be serialized.
B. An object serialized on one JVM can be successfully deserialized on a different JVM.
C. The values in fields with the volatile modifier will NOT survive serialization and deserialization.
D. The values in fields with the transient modifier will NOT survive serialization and deserialization.
E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
答案:BDE
參考:10-5-2 ObjectInputStream與ObjectOutputStream類別
-----------------------------------------------------------------------------------------
B. An object serialized on one JVM can be successfully deserialized on a different JVM.
如果一個物件在一個jvm上做序列化就可以在另一個jvm上做反序列化
ex:執行一個程式產生一個新的jvm,這個程式是把物件寫入檔案中...
再開一個程式把產生另一個jvm,反序列化就是檔案取出
D. The values in fields with the transient modifier will NOT survive serialization and deserialization.
屬性加上transient的修飾詞 在序列化過程中就不會保留它的值,因此在做反序列化時
會取出系統預設的初始值,換句話說不會保留原有的值
E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
如果現在要序列化一個物件,該物件所屬類別的父類別不需要實做java.io.Serializable,
但該物件是需要實做
A. Objects from classes that use aggregation cannot be serialized.
B. An object serialized on one JVM can be successfully deserialized on a different JVM.
C. The values in fields with the volatile modifier will NOT survive serialization and deserialization.
D. The values in fields with the transient modifier will NOT survive serialization and deserialization.
E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
答案:BDE
參考:10-5-2 ObjectInputStream與ObjectOutputStream類別
-----------------------------------------------------------------------------------------
B. An object serialized on one JVM can be successfully deserialized on a different JVM.
如果一個物件在一個jvm上做序列化就可以在另一個jvm上做反序列化
ex:執行一個程式產生一個新的jvm,這個程式是把物件寫入檔案中...
再開一個程式把產生另一個jvm,反序列化就是檔案取出
D. The values in fields with the transient modifier will NOT survive serialization and deserialization.
屬性加上transient的修飾詞 在序列化過程中就不會保留它的值,因此在做反序列化時
會取出系統預設的初始值,換句話說不會保留原有的值
E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
如果現在要序列化一個物件,該物件所屬類別的父類別不需要實做java.io.Serializable,
但該物件是需要實做
訂閱:
文章 (Atom)