Prof. Dr. A. Poetzsch-Heffter Dipl.-Inform. Markus Reitz
Technische Universität Kaiserslautern Fachbereich Informatik AG Softwaretechnik
Practice Sheet 6: Fortgeschrittene Aspekte objektorientierter Programmierung (SS 2008)
Date of Issue: 20. Mai 2008 Deadline: 26. Mai 2008 (until 10 a.m. as PDF via E-Mail)
Exercise 1 Combinations
In exercise 3 of the previous practice sheet, aPermutatorclass had to be implemented. After having analysed the overall principle of the algorithm used by classPermutations, you should now be able to design and implement other combinatorical algorithms.
a) Implement a classCombinatorwhich provides the following features
1. For a given collection of elements implementing interfaceIterable<T>, theCombinatorclass provides an iterator that allows to gather all collections containing elements of typeT. The iterator creates a collection by selecting exactly one element from eachIterable<T>instance contained in the initial collection.
2. The implementation has to provide an usage interface as exemplified by the code fragment
L i s t<L i s t<I n t e g e r>> l i s t=new A r r a y L i s t<L i s t<I n t e g e r> >() {{
add ( a s L i s t ( 1 , 2 ) ) ; add ( a s L i s t ( 3 , 4 , 5 ) ) ; add ( a s L i s t ( 6 , 7 ) ) ; } } ;
f o r( C o l l e c t i o n<I n t e g e r> c u r r e n t : new C o m b i n a t o r<I n t e g e r>( l i s t ) ) S y s t e m . o u t . p r i n t l n ( c u r r e n t ) ;
which results in the output (or a permutation thereof)
[1, 3, 6]
[2, 3, 6]
[1, 4, 6]
[2, 4, 6]
[1, 5, 6]
[2, 5, 6]
[1, 3, 7]
[2, 3, 7]
[1, 4, 7]
[2, 4, 7]
[1, 5, 7]
[2, 5, 7]
b) Explain thetry { ... } finally { ... }idiom used within thenext()method in the source code of class Permutations. Which value is returned by the following code fragment?
. . . t r y {
r e t u r n 4 2 ; }
f i n a l l y { r e t u r n 1 7 0 1 ; }
. . .
Exercise 2 Wildcards / Reflection in the Context of Generics
a) Implement a generic static methodcopyhaving the following signature
p u b l i c s t a t i c <. . .> C o l l e c t i o n<. . .> c o p y ( C o l l e c t i o n<. . .> s o u r c e , C o l l e c t i o n<. . .> d e s t i n a t i o n )
When invoked, this method shall copy all elements from the source collection to the given destination collection.
Replace each ellipsis so your implementation provides maximum reusability without violating type correctness.
b) Because of thetype erasuretechnique, generic type information is not available for instances of generic types in case of Java. However, Java’s reflection capabilities provide a limited set of functionality to gather information concerning a generic type’s type variables, implemented generic interfaces and so on. Collect and explain the relevant concepts and methods provided by Java’s reflection API.