Download APJP2015Final!Solution

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

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

Document related concepts
no text concepts found
Transcript
Advanced Programming on Java Platform: Final Examination
姓名:______________
學號:__Solution_________
12/21 2015
分數:______________
I (75 pts) 單選題 debcd bdcba adbbc daccb (b|c)cdbb dbbab
1.
2.
Which of the following declaration is permitted in a generic class C<T> declaration?
a)
T[] ts = new T[10] ;
b)
List<T>[] lst =
new ArrayList<>[10];
c)
T t = new T();
d)
List<T>
(List<T>[]) new ArrayList<?>[10]
Which of the following methods of a thread should not be used for it may cause inconsistency of the system?
a) sleep()
3.
b) yield()
c) suspend()
d) join()
e) stop()
Which of the following methods will cause a thread enter the TIMED_WAITING state?
a) wait()
4.
lst =
b) sleep(long)
c) yield()
d) run()
e) start()
What is the resulting state of a thread when it executes a synchronized statement without entering its body
immediately?
a) RUNNABLE
5.
b)TIMED_WAITING
c) BLOCKED
d) WAITING
Which of the following method is NOT final (and hence can be overridden) in the common super type Enum of
all Java enum type?
a) compareTo(E)
6.
c) ordinal()
d) toString()
Which of the following method is static in java.lang.Thread?
a) join()
7.
b) hashCode()
b) sleep(long)
b) run()
d) start()
Which of the following statement is correct as to the interruption of a thread?
a)
If a RUNNABLE thread is interrupted, it will receive an InterruptedException immediately.
b)
A thread will not receive an InterruptedException if it is in the WAITING state.
c)
A thread will receive an InterruptedException if it is in the BLOCKED state.
d)
The invocation of sleep(.) will cause a RUNNABLE thread to receive an InterruptedException immediately
if it is interrupted before sleep(.) is called.
8.
Which of the following is statement can be used to create a fair Lock?
a) Lock lock = new Lock();
b) Lock lock = new ReentrantLock();
c)
Lock lock = new ReentrantLock(true);
d) Lock lock = new ReentrantLock(false);
9.
Which of the following statement can be used to create a condition on a lock object lck ?
a) Condition condition = lck.getCondition();
b) Condition condition = lck.newCondition();
c)
Condition condition = Lock.newCondition(lck);
d) Condition condition = Lock.getCondition(lck);
10.
Which method should you use in a synchronized method to change a waiting thread to RUNNABLE state?
a) notify();
11.
b) signal();
c) notifyAll();
d)signalAll();
Which ExecutorService should you use to enable parallel execution of mutlithreads for a task ?
a)
new ForkJoinPool()
b) Executors.newCachedThreadPool()
c)
Executors.newScheduledThreadPool()
d) Executors.newFixedThreadPool()
1
12.
Which of the following methods cannot be used outside of a synchronized methods or statement?
a)
13.
b) toString
c) equals
d) wait
e)
lock
Which of the following types is NOT a subclass of java.util.Map?
a)
14.
clone
java.util.HashMap
b) java.util.SortedMap
c) java.util.Hashtable
d) java.util.TreeMap
Which of the following synchronizers is suitable for the management of a fixed amount of mutual exclusive
resources?
a)
15.
Barrier
b) Semaphore
c) CountDownLatch
(d) Exchanger
e) SynchroizedQueue
Which of the following synchronizers in Java can be used to block all arriving threads until a certain number of
events have happened?
b)
16.
Barrier
18.
c) CountDownLatch
(d) Exchanger
e) SynchroizedQueue
Which of the following class allow concurrent updates of the underlying data structure?
a) Hashtable
17.
b) Semaphore
b) StringBuffer
c) HashMap
d) ConcurrentHashMap
Which of the following queue is bounded (can contain only limited number of elements)?
a) ArrayBlockingQueue
b) LinkedBlockingQueue
c)
d) PriorityQueue
PriorityBlockingQueue
Which of the following method can be used to add an element to a blocking queue and will wait until space is
available if the queue is full?
a) add()
19.
b) offer()
c) put()
d) take()
Which of the following statement has no compile error ?
a) Map<Long,Long> m = new Map<>();
b) HashMap<Number,Number> list = new HashMap<Long, Number>();
c)
Map<Long, Long> list = new TreeMap<>();
d) HashMap<int,int> list = new HashMap<>();
20.
21.
To declare an interface named A with two generic types, use
a) public interface A<E> { ... }
b) public interface A<E, F> { ... }
c) public interface A(E) { ... }
d) public interface A(E, F) { ... }
Given the following method:
void m( Function<_______,_________>
f) { …;
Tt=…;
U u = f.apply(t) ; …}
Which of the following can be declared as the type of f without causing compiler time error?
22.
a)
Function<? extends T, ? extends U>
b) Function<? extends T, ? super U>
b)
Function<? super T, ? extends U>
d) Function<? super T, ? super T> .
Which of the following method would cause compile error if we put the code : "E e = lst.get(0);"
into their
bodies?
a)
public <E> void m0(List<E> lst) {… }
b) public <E> void m1(List<? extends E> lst) {… }
c)
public <E> void m2(List<? super E> lst) {… }
d) public void m2(List lst) {… }
23.
24.
Which of the following statement is incorrect ?
a)
Integer[] is a subtype of Number[]
b) Integer[] is a subtype of Object
b)
Object[] is a subtype of Object
d) int[] is subtype of long[]
Which of the following is a meta annotation that is used to specify the location of a program in which an
2
annotation can be kept?
a) @Rentation
25.
c) @Documented
d) @Inherited
e) @Deprecated
Which of the following functional interfaces can be matched by the lambda expression: (e1,e2) -> e2 ?
a) Function<T,U>
26.
b) @Target
b) BiFunction<T,U>
c) Supplier
d) BiConsumer
To sum up all intgers in an IntStram object nums, you use the invocation : nums.reduce(0, xxx). Then what
interface the lambda expression xxx should match?
a) UnaryOperator
27.
b) BinaryOperator
c)
BiConsumer
d) IntBinaryOperator
Which of the following method can be used to detect if a currently executed thread t is interrupted without
causing the interrupt status bit to be reset?
a) Thread.interrupted()
28.
b) t.isInterrupted()
c) t.interrupt() (d) Thread.interrupt()
In order to enforce that every update of a field x of long value is readable by later read operation, which
declaration of x should you choose?
a)
29.
30.
transient long x;
b) volatile long x;
c) pubic synchronized
long xl
d)
private long x
;
Which of the following is a correct Java statement? Assume all types have been imported.
a)
Runnable r = () -> {} ;
b) Comparable<Number> c = (s1,s2) -> s1.length() < s2.length() ;
c)
Function<String, Integer> f = String::length + 1 ;
d) Callable<String> c = (s) -> s ;
Which of the following interfaces is NOT a functional interface?
a) java.util.function.BiFunction
b) java.util.List
c) java.util.function.Predicate
d) java.lang.Runnable
II 程式設計/填充 (87 pts)
1.[Stream] [16 pts] Fill in the following blanks to achieve the effect as described in the comments.
String []
int sum
ws = {"abc", … } ;
=
Arrays.__stream___ (ws)
. __filter( x -> x.lenght() % 2 == 1)__
// get a Stream<String> object from ws.
// get a Stream<String> from preceding one by removing elements of odd length.
.__map( x -> x.length)__// get a Stream<Integer> object from preceding one by transforming every element w into w.length().
. _reduce(0, (x,y) -> x+y )__ ;
// sum all integers in the stream use reduce().
2.[Stream] [8 pts] Given a list of Integers nums, return a map m of type Map<Boolean, List<Integer>> such that m.get(true) return
the list of integers in nums which are positive and m.get(false) return the lsit of all non-positive Integers in nums.
Map<Booelan, List<Integer>> partition(List<Integer> nums ) { // using stream API
return
nums. ___stream()______
// from List<Integer> to stream<Integer>
.collect(_Collectors.partitoningBy(x -> x > 0) ). // partition numbers in stream into positive and non-positive parts
3. [Thread+lambda] [18pts]Generate and start two threads named "POdd" and "PEven", respectively. POdd will perform the task
pOddTask, which will prints to console all positive odd numbers  an input value bound parsed from args[0] and PEven will
perform the task pEvenTask, whch will print all positive even number  bound.
public class P4 {
public int bound
;
3
// print all positive odd number <= bound
protected Runnable pOddTask = _() -> {
for(int k = 1; k <= bound; ) { out.println(k) ; k += 2 } } ;
// print all positive even number <= bound
protected Runnable pEvenTask = ____() -> {_
for(int k = 2; k <= bound; ) { out.println(k) ; k += 2 } };
public void p4(int bound){
this.bound = bound ;
new Thread(pOddTask, “pOdd” ) ;
Thread pOddThread =
Thread pEvenThread =
pOddThread.start();
// remember to assign a name to each thread.
new Thread(pEvenTask, “pEven” ) ;
// start both threads using method start()
pEvenThread.start();
// wait until both threads terminate before p4() can return!
__pOddThread.join() ;______________
__pEvenThread.join();______________
}
public static void main(String[] args ) throws Exception{
int bound =
_Integer.parseInt(args[0]) ;_____
// convert arg[0] from String to int.
P4 p4 = new P4(); p4.p4(bound);
// P5 p5 = new P5(); p5.bound = bound;
p.p5();
// used for next problem!
}}
4. [15pts][ExecutorService/Exectuor] Define a class named P5 which Extends the class P4 given in preceding problem and
provides a new method p5(). The method p5() will perform basically the same thing as p4(), however, in a different way. Instead
of creating threads, p5 need to generate an instance of ExecutorService (note: it's an interface and has many implementations)and
submit the tasks POddTask and pEvenTask via the instance.
public class P5 extends P4 {
public void p5() {
ExecutorService es = __ExecutorServices.newCachedThreadPool();______ ;
es. _execute(pOddTask)_______
es._submit(pEvenTask)_______
es._shutdown()__________
; //submit pOddTask
; //submit pEvenTask
; //stop accepting further submission/execute requests.
// wait until both tasks complete before p5() can return.
_while(!(es.isTerminated())) try { Thread.sleep(20) ;} catch(Exception e){} ;_
}
5. [Generics][15pts] Define a generic class called Pair with two type Parameters T1 and T2 which is intended to store two values
of type T1 and T2, respectively. Pair has two fields: the first one storing a value of type T1 is called fst and the second storing a
value of type T2 is called snd. Your implementation of Pair must not cause errors in the following use of the class.
Pair<String, Integer> pair1 = new Pair<>("abc", 3) ;
Pair<Integer, String> pair2 = new Pair<>(4, "abcd") ;
System.out.println( pair1.fst .equals("abc") )
// return true
4
System.out.println( pair1.snd .equals(new Integer(3) )
// return true
public class Pair_<_T1,T2__> { //required members: 2 fields + 1 constructor
_public T1 fst;
_________
_public T2 snd;_________
__public Pair(T1 t1, T2 t2) { fst = t1; snd = t2;}__
}
6.[Generics][15pts] Modify the Pair class given in the above problem so that we can compare and test equality of two Pair objects.
To enable these operations, its components fst and snd must be Comparable as well. As a result, the type T1 and T2 must be
bounded by some type.
public class Pair<_T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2> >
implements
Comparable<_Pair<T1,T2>______>{ // require 3 additional members
// Declaration of fst, snd and Constructor are assumed to have been given in your answer to preceding problem.
public boolean equals(Object o) { // give your definition________________
__if( ! o instanceof Pair<?,?>) return false;_
Pair<T1,T2> p2 = (Pair<T1,T2>) o ;
return fst.equals(p2.fst) && snd .equals(p2.snd) ;
} public int hashCode() {
return fst ^ snd ;
// the only requirement : Equal objects must have same hashCode();
}
// Compare two pairs (s1,s2) and (t1,t2) lexicographically, i..e, (s1,s2) <(t1,t2) iff (s1< t1) or (s1 == t1) and (s2 < t2)
// and (s1,s2) == (t1,t2) iff s1==t1 and s2==t2.
public int compareTo( Pair<T1, T2> p ) {
int cmp = fst.compareTo(p.fst) ;
if(cmp != 0) return cmp ;
return snd.compareTo(p.snd) ;
}}
5