Download APJP2016Final!Solution

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

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

Document related concepts
no text concepts found
Transcript
Advanced Programming on Java Platform: Final Examination
姓名:______________
I (70 pts) 單選題
1.
cdcba dccba abcdb
bbdcb
分數:______________
baaac ccacd
cdbca
Which of the following types can be used to read bytes from a stream?
a)
2.
學號:___Solution________
11/28 2016
Writer
b) Reader
c) InputStream
d) OutputStream
Which of the following type allow you to write primitive values directly into an output stream without the need
to make any conversion?
a)
3.
BufferedWriter
What is the type of
a)
5.
PrintWriter
b) InputStreamReader
d) DataOutputStream
c) OutputStreamWriter
d) PipedOutputStream
System.out?
b) PrintStream
b) Queue
c) List
c) BufferedWriter
d) BufferedStream
d) Set
e) Map
Which of the following types is NOT a subtype of java.til.List?
a) java.util.ArrayList
7.
c) FileWriter
Which of the following java types in java.util package is NOT an interface ?
a) Vector
6.
b) PipedOutputStream
Which of the following types can transform the character data you wrote to it into a byte stream?
a)
4.
BufferedWriter
b) java.util.LinkedList
c) java.util.Vector
d) java.util.PriorityQueue
Which of the following declarations use raw type?
a) Stack<String> list = new Stack<String>();
b) List<Object> list = new LinkedList<Object>();
c)
List list = new ArrayList();
d) Set<Integer> list = new TreeSet<Integer>();
8.
Which of the following statement has no compile error ?
a) Stack<Object> list = new Stack<Integer>();
b) Stack<Number> list = new Stack<Integer>();
c)
Stack<Long> list = new Stack<>();
d) Stack<int> list = new Stack<>();
9.
10.
To declare an interface named If with two generic type parameters, use
a) public interface If<E> { ... }
b) public interface If<E, F> { ... }
c) public interface If(E) { ... }
d) public interface If(E, F) { ... }
Which of the following method would cause compile error if we put the code : "s.push(e) ;"
a)
into their bodies?
public <E> void m1(Stack<? extends E> s, E e) {… }
b) public <E> void m2(Stack<? super E> s, E e) {… }
c)
public void m3(Stack s, E e) {… }
d) public <E> void m4(Stack<E> s, E e) {… }
11.
Which of the following is a meta annotation that is used to specify the duration time during which an annotation
can be kept?
a) @Rentation
b) @Target
c) @Documented
1
d) @Inherited
e) @Deprecated
12.
Given the following declaration: @interface T { int p1() default 10;
String value();}, which of
the following is not a correct use of the annotation?
a)
13.
b) @T("abc")
c) @T(value="abc", p1="10")
d) T(p1=10, "abc")
Which of the following stream methods can be used to generate another stream?
a)
14.
@T
forEach
b) collect
c)
map
d) findFirst
Suppose es is an instance of the type Stream<Employee>. Then Which of the following invocation can be used to
get all instances of Empolyee in the stream as an instance of Employee[]?
15.
a)
es.collect(Collectors.toArray())
b) es.toArray()
c)
es.collect(Collectors.toList()).toArray()
d) es.toArray(Employee[]::new)
Which of the following meta annotation is used to specify the positions where an annotation can be placed?
a)
16.
@Rentation
c) @Documented
d) @Inherited
e) @Deprecated
Which of the following functional interfaces can be matched by the lambda expression: (e1,e2) -> e1 != e2 ?
a) BiFunction
17.
b) @Target
b) BiPredicate
c) Supplier
d) BiConsumer
To sum up all numbers in a Stram<Integer> object nums, you use the invocation : nums.reduce(0, xxx). Then
which of the following interfaces the lambda expression xxx should match?
a) UnaryOperator
18.
19.
b) BinaryOperator
c)
BiConsumer
d) Function
Which of the following is permitted to occur within a generic class C<E> declaration?
a)
E[] es = new E[0] ;
b)
List<E>[] lst =
new ArrayList<>[5];
c)
E e = new E();
d)
List<E>[] lst =
(List<E>[]) new ArrayList<?>[5]
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, Number> list = new TreeMap<>();
d) HashMap<int, double> list = new HashMap<>();
20.
Which of the following methods is NOT final (and hence can be overridden) in the common super type Enum of
all Java enum type?
a) compareTo(E)
21.
22.
b) toString()
c)
hashCode()
d) ordinal()
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
Which instances of the following interfaces can be filled in the underlined blank without causing any error?
Arrays.asList(1,2,3,5).stream().filter(____)
23.
a)
java.uitl.function.Predicate
b) java.io.FileNameFilter
c)
java.uitl.function.Consumer
d) java.lang.Runnable
To avoid the serialization of a field x of long type in a serializable class, how should we declare it?
a)
24.
transient long x;
b) volatile long x;
c) synchronized long x;
d)
final 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 ;
2
25.
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 compile-error?
26.
a)
Function<? extends T, ? extends U>
b) Function<? extends T, ? super U>
c)
Function<? super T, ? extends U>
d) Function<? super T, ? super T> .
Suppose aPath is a Path object and out = Files.newOutputStream(aPath, CREATE ), then what is true about the
output stream?
27.
a)
The method will throw an exception if aPath is not an existing file.
b)
The method will throw an exception if aPath is an existing file.
c)
The method will truncate existing content if aPath is an existing file.
d)
The output stream will append written content to the end of existing file contents.
If p1 = Paths.get("c:/a/b/c) and p2 = Paths.get("c"), then what is the output of
System.out.print(p1.resolve(p2))?
a)
28.
c:\a\b
b) c:\a\b\
c) c:\a\b\c\c
d) c
If p1 = Paths.get("/a/b/c) and p2 = Paths.get("c/d"), then what is the output of
System.out.print(p1.resolveSibling(p2))?
a)
29.
/a/b/c/d
b) /a/b
c) /a/b/c/c/d
d) a/b/d
If p1 = Paths.get("/a/b) and p2 = Paths.get("/a/b/c/d"), then what is the output of
System.out.print(p1.relativize(p2))?
a)
30.
32.
33.
b)
/a/b
c)
c/d
d)
/c/d
If p1=Paths.get("c:/a/b/c/c/d") then what is the output of System.out.print(p1.subpath(0,2))?
a)
31.
a/b
C:\a
b) \a\b\c
c) C:\a\b
d) a\b
Let  denote the subtype relation of Java type system. Then which of the following is correct?
a)
int  Number
d)
List<String>  List<Object>
b)
Object  Object[]
c) Integer[] Number[]
Let  denote the subtype relation of Java type system. Then which of the following is correct?
a)
List<Object>  List<? extends Number>
b) List<? extends Number> 
c)
List<Integer>  List<? super Number>
d) List<? extends Integer>

a)
35.
List<? extends Number>
If we call writeByte(255) on a DataOutputStream, then what will be read in if we call readByte() on the same
source as a DataInputStream?
34.
List<? super Number>
255
b) -1
c)
127
d) -128
Which of the following statements are correct? Suppose s is a stream.
a)
s.forEach(e->{}).forEach(e->{}) ;
b) s.forEach(e->{}); s.forEach(e->{}) ;
c)
s.peek(e->{}).peek(e->{}) ;
d) s.peek(e->{}); s.peek(e->{}) ;
Which of the following interfaces is a functional interface?
a) java.lang.Comparable
b) java.util.Collection
c) java.io.Serial
d) java.lang.Clonable
3
II 程式設計/填充 (70 pts)
1. [javaNIO; 10pts] Complete the following method which, when passed a text file name fname and a string str, can count how
many lines in the named file contain the substring str. Note: java.nio.files.Files has a method lines(Path) returning all lines as an
object of type Stream<String>, and has a method readAllLines(Path) returning all lines as an object of type List<String>
static int m(String fname, String str ) {
return
Files.lines(Paths.get(fname))
.filter( line -> line.contains(str))
.count() ;
}
2. [generics; 10pts] Design a generic method max using bounded wildcard which can accepting an input lst of type List<Integer>
or List<Number> and return the maximum of element in the list as a double. Note: The method doubleValue of class Number
can return
static
its value as a double.
double max( List<__? extends Number__> lst) {
if(lst == null || lst.isEmpty()) return Double.NEGATIVE_INFINITY ;
double rlt = lst.get(0).doubleValue() ;
for(Number n : lst) {
if(rlt < n.doubleValue()) rlt = n.doubleValue() ; }
return rlt;
}
3. [10pts] Fill in the following blanks with lambda expressions to complete the task of sorting an array/list of strings in different
ways:
final String[] fruits = new String[] {"Apple", "Orange", "Tomato", "Watermelon", …} ;
// sort strings in fruits by their word length
Arrays.sort(fruits,
___(e1,e2) -> e1.length() - e2.length()___________) ;
List<String> fruits2 = Arrays.asList(fruits); // sort strings in words2 by the number of characters: 'w' occurring in them.
Collections.sort(fruits2, __(w1,w2) -> { int c1 = 0, c2 = 0;
for(int k =0; k < w1.length(); k++) if( w1.charAt(k) == ‘w’) c1++ ;
for(int k =0; k < w2.length(); k++) if( w2.charAt(k) == ‘w’) c2++ ;
return c1-c2;__}___) ;
4.
[javaIO; 12 pts] Suppose a File named 'nums.data' is constructed as follows:
DataOutput dout = new DataOutputStream(new FileOutputStream("nums.data")) ;
int n = (int) (1000 * Math.random());
for( int k = 0; k < n; k++) dout.writeInt( 1000 * Math.random()) ;
dout.close();
Complete the following method so that we can find the sum of all integers written to the file by the above code if we invoke the
method sumOfIntsInAFile("nums.data"). Note: If we reach the end of a file without completing the reading of an integer, the
read… method will throw an EOFException.
static int sumOfIntsInAFile(String filename ) throws Exception {
_DataInput_
din =
new _DataInputStream__ ( new FileInputStream("nums.data") );
4
int
rlt = 0 ;
try { whilt (true) { rlt += din.readByte() ; }
catch(EOFException e) {}
return rlt;
}
5. [18 pts] Fill in the following blanks to achieve the effect as described in the comments.
String []
ws = {"abc", … } ;
String[] ws2= Arrays.___stream__ (ws)
. _filter(e-> e.length() >= 3)_
// get a Stream<String> object from ws.
// get a Stream<String> from preceding one by removing those elements with length < 3.
._map(String::toLowerCase)___// get a Stream<String> object from preceding one by transform every element w into
//
w.toLowerCase()
. _toArray(__String[]::new____) ;
// get an array from the preceding stream.
// use System.out.println to print all Strings in ws2 to the console
Arrays.asList(ws2). __stream()_____________
// get a Stream<String> object from a List<String> object
.forEach(__System.out::println____ ) ; // print out all elements of the stream
6. [10] Use the static Stream.generate(Supplier<Double>) method to generate an Integer sequence : start, start*ratio, start*ratio2 +
, …., start* ratio(size-1).
List<Integer> intSeq(double start, double ratio, int size ) {
return
Stream.generate(
new Supplier<Double>() {___double value = start ;___________
__public Double get() {_____
______double old =
_____
value;______
value *= ration ;__
return old ; }
}) ._limit(size)_________
// get the first size elements from the preceding stream
.collect(__Collectors.toList()_____) ;
// convert Stream<Double> to List<Double>
5