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

第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的值,而不會影響對方

第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介面

第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 執行緒的同步性與安全性

第237題




第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(){

第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介面

第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行.

第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作為參數.

第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類別

第240題


第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介面

第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介面

第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介面

第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 執行緒的同步性與安全性

第218題


第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 區塊,這樣同時間就只能有一條執行緒.

第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 區塊 鎖定物件.

第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類別

第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

第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() 主執行緒 會等 副執行緒結束後再執行.

第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

第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做完後才繼續

第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

第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的內容, 例如 方法,或區塊.

第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

第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.



答案:
Output

(no more output)
started
ran
interrupting
ended

參考:13-3 Runnable介面

---------------------------------

23. 主執行緒 睡2秒, 副執行緒稅1秒, 所以先印出ran 再印 interrupt.

第217題

Place the code into the GenericB class definition to make the class compile successfully.

答案:


參考:12-3 泛型

--------------------------------------------------------

第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, 印出就不用再轉型.

第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集合

第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, 已超出範圍

第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()的內容.
實作排序方法只能用一種排序方法. (實作順序,就不能用逆序).

第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, 變成加入父類別.

第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.

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()方法的改寫

第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]

第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行

第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]

第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

第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集合

第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); //一樣的不給放,所以只有三個可放入,但沒有順序的依據

第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.


答案:
參考: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()方法的改寫
-----------------------------------------------------------------
將所有的屬性放入改寫會比較恰當

第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

第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這一個元素可以移除

第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, 所以失敗

第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

第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

第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()//只會取出下一個元素的值不會移除該元素

第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 泛型

第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(). 並沒有此方法.

第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 泛型

第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物件, 所以編譯失敗.

第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()方法的改寫

第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 並回傳

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 泛型

第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類別

第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

第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增加存取速度.

第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 各種集合的特色

第184題

Placeeach Collection Type on the statement to which it applies.

答案:



參考:12-4 各種集合的特色、12-5 Map的功能與架構
----------------------------------
List, 可以用index.
Map, 定義了依各get方法 並用Key取直
Queue, 保留元素的順序並做處理.
Set, 用equals來檢查,不可以有相同值的元素.

第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()