Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 55cdd3f

Browse files
committed
Added answers to Generics. Added answers to Version Specific.
1 parent 7f23540 commit 55cdd3f

File tree

3 files changed

+318
-19
lines changed

3 files changed

+318
-19
lines changed

Java Generics.txt

Lines changed: 314 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,322 @@
22
Generics
33
------------------------------------------------------------------------------------------
44

5+
Very good collection of Q&A about Java Generics can be found
6+
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
7+
8+
9+
Questions
10+
-------------------------------
11+
512
1. What is Generics in Java ? What are advantages of using Generics?
13+
14+
They allow "a type or method to operate on objects of various types while providing compile-time type safety." A common use of this feature is when using a Java Collection that can hold objects of any type, to specify the specific type of object stored in it.
15+
16+
A class is generic if it declares one or more type variables.
17+
618
2. How Generics works in Java ? What is type erasure ?
19+
20+
The type safety is ensured during the compile time. In run time the information about type arguments is erased. The type arguments are replaced by their narrowest superclass. For unbounded parameters -- Object. For bounded -- the declared bound.
21+
722
3. What is Bounded and Unbounded wildcards in Generics ?
8-
4. What is difference between List<? extends T> and List <? super T> ?
9-
5. How to write a generic method which accepts generic argument and return Generic Type?
10-
6. How to write parametrized class in Java using Generics ?
11-
7. Write a program to implement LRU cache using Generics ?
23+
24+
The wildcard type is signified by "?" in Java. Classes parametrized by wildcard are usually read as "class of some type", e.g. List<?> is read List of some type.
25+
26+
A wildcard parameterized type is an instantiation of a generic type where at least one type argument is a wildcard. Examples of wildcard parameterized types are Collection<?>, List<? extends Number>, Comparator<? super String> and Pair<String,?>.A wildcard parameterized type denotes a family of types comprising concrete instantiations of a generic type. The kind of the wildcard being used determines which concrete parameterized types belong to the family. For instance, the wildcard parameterized type Collection<?> denotes the family of all instantiations of the Collection interface regardless of the type argument. The wildcard parameterized type List<? extends Number> denotes the family of all list types where the element type is a subtype of Number. The wildcard parameterized type Comparator<? super String> is the family of all instantiations of the Comparator interface for type argument types that are supertypes of String.
27+
28+
A wildcard parameterized type is not a concrete type that could appear in a new expression. A wildcard parameterized type is similar to an interface type in the sense that reference variables of a wildcard parameterized type can be declared, but no objects of the wildcard parameterized type can be created. The reference variables of a wildcard parameterized type can refer to an object that is of a type that belongs to the family of types that the wildcard parameterized type denotes.
29+
30+
4. What is wildcard prameter
31+
32+
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
33+
34+
5. What is difference between List<? extends T> and List <? super T> ?
35+
36+
The first list may contain elements of type T or any of its subtypes.
37+
The second list may contain elements of type T or any of its supertypes.
38+
39+
For any type X such that X is a subtype of T or T itself
40+
List<X> is a subtype of List<? extends T>
41+
42+
For any type Y such that Y is a supertype of T or T itself
43+
List<Y> is a subtype of List<? super T>
44+
45+
List<?> is supertype of any parametrized list.
46+
47+
6. How to write a generic method which accepts generic argument and return Generic Type?
48+
49+
Generic method in a generic class
50+
51+
public class SomeClass<T>{
52+
private T value;
53+
54+
// T is already declared
55+
// since it's type parameter of the class
56+
public T doSomething(){...}
57+
58+
// U has to be declared since it's not type parameter of the class
59+
public <U> List<U> createSingleElementList(U arg){
60+
List<U> result = new ArrayList<U>();
61+
result.add(arg);
62+
return result;
63+
}
64+
}
65+
66+
Static generic method
67+
68+
public static <T> T doSomething(T value){...}
69+
70+
7. How to write parametrized class in Java using Generics ?
71+
72+
class SomeClass<T> extends SomeSuperClass implements SomeInterface
73+
class SomeClass<T extends Comparable<? super T>>
74+
class SomeClass<K,V>
75+
1276
8. Can you pass List<String> to a method which accepts List<Object>
77+
78+
No. You cannot do this since there List<Object> is not a superclass of List<String>
79+
1380
9. Can we use Generics with Array?
14-
10. How can you suppress unchecked warning in Java ?
15-
11. Difference between List<Object> and raw type List in Java?
16-
12. Difference between List<?> and List<Object> in Java?
17-
13. Difference between List<String> and raw type List.
18-
14. What does the Class Enum<E extends Enum<E>> ensure?
19-
15. Is <T> List<? extends T> x() a useful signature?
20-
16. Examples of a valid generic type that cannot be expressed with the Java type system and will lead to compiler warnings.
21-
17. Examples where the java compiler will/will not infere the generic type? (examples of code where the compiler will infere the wrong type)
22-
18. What generic type information is not erased and can be retrieved from the byte code? (Super type tokes are one application)
23-
19. What's APT (use cases when not to use reflection)?
81+
82+
No. One cannot use generic types with arrays. See below other limitations of generic types.
83+
84+
10. What are limitations of Generics
85+
86+
http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html
87+
88+
Cannot Instantiate Generic Types with Primitive Types
89+
Cannot Create Instances of Type Parameters
90+
Cannot Declare Static Fields Whose Types are Type Parameters
91+
Cannot Use Casts or instanceof with Parameterized Types
92+
but you can use (obj instanceOf SomeClass<?>)
93+
Cannot Create Arrays of Parameterized Types
94+
Cannot Create, Catch, or Throw Objects of Parameterized Types
95+
Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type
96+
97+
11. How can you suppress unchecked warning in Java ?
98+
99+
@SuppressWarnings("unchecked")
100+
101+
12. Difference between List<Object> and raw type List in Java?
102+
103+
List<Object> explicitly states that it contains objects. The type checks are on. Using raw types disable checking even outside of their own declarations. This would happen if we used raw List.
104+
105+
Another thing that differs significantly is that List<Object> is not covariant with any other parametrized list, while List is.
106+
107+
Example:
108+
109+
public static void printList(List l){
110+
for (Object obj : l) {
111+
System.out.println(obj);
112+
}
113+
}
114+
115+
public static void printObjectList(List<Object> l){
116+
for (Object obj : l) {
117+
System.out.println(obj);
118+
}
119+
}
120+
121+
public static void main(String[] args) {
122+
List<Object> objList = Arrays.asList((Object)new Integer(5), (Object)"x");
123+
List<String> stringList = Arrays.asList("A","B","C");
124+
List<Integer> intList = Arrays.asList(1, 2, 3);
125+
126+
printList(objList); // valid
127+
printList(stringList); // valid
128+
printList(intList); // valid
129+
130+
printObjList(objList); // valid
131+
printObjList(stringList); // invalid. compiler error
132+
printObjList(intList); // invalid. compiler error
133+
}
134+
135+
13. Difference between List<?> and List<Object> in Java?
136+
137+
List<Object> -- only list of objects is allowed.
138+
List<?> -- any parametrized list and the raw List type is allowed
139+
140+
14. Difference between List<String> and raw type List.
141+
142+
List<String>
143+
Only accepts String arguments in methods like add(), set()
144+
Returns String values in get()
145+
Takes care casting the stored values to correct class
146+
Performs the type checks
147+
148+
15. Difference between List<?> and raw type List.
149+
150+
The raw type and the unbounded wildcard parameterized type have a lot in common. Both act as kind of a supertype of all instantiations of the corresponding generic type. Both are so-called reifiable types. Reifiable types can be used in instanceof expressions and as the component type of arrays, where non-reifiable types (such as concrete and bounded wildcard parameterized type) are not permitted.
151+
152+
In other words, the raw type and the unbounded wildcard parameterized type are semantically equivalent. The only difference is that the compiler applies stricter rules to the unbounded wildcard parameterized type than to the corresponding raw type. Certain operations performed on the raw type yield "unchecked" warnings. The same operations, when performed on the corresponding unbounded wildcard parameterized type, are rejected as errors.
153+
154+
16. Is <T> List<? extends T> x() a useful signature?
155+
156+
From docs.oracle.com: Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards. In this specific case the returning list could be thought as of read-only. But the client code would still be able to add null, to clear the list or to remove the elements from the list. Trying to add element would result in compiler errors regarding the wildcard capture errors
157+
In this specific case one cannot be sure about which exact type of list will be returned from the method x(). Is it going to be List<T> or maybe List<S> (where S extends T)?
158+
159+
17. What restrictions are placed on method overloading?
160+
161+
Two methods with different generics cannot overload each other e.g. this is not allowed (again because of type erasure):
162+
163+
void print(List<String> strings);
164+
void print(List<Double> doubles);
165+
166+
167+
18. Examples of a valid generic type that cannot be expressed with the Java type system and will lead to compiler warnings.
168+
169+
170+
171+
19. Examples where the java compiler will/will not infere the generic type? (examples of code where the compiler will infere the wrong type)
172+
173+
174+
175+
20. What generic type information is not erased and can be retrieved from the byte code?
176+
177+
178+
179+
21. What's APT (use cases when not to use reflection)?
180+
181+
182+
183+
22. What does the Class Enum<E extends Enum<E>> ensure?
184+
185+
186+
187+
23. If the compiler erases all type parameters at compile time, why should you use generics?
188+
189+
190+
191+
Write yourself
192+
-------------------------------
193+
194+
1. Write a program to implement LRU cache using Generics ?
195+
196+
DONE
197+
198+
2. Write a generic method to count the number of elements in a collection that have a specific property (for example, odd integers, prime numbers, palindromes).
199+
200+
DONE
201+
202+
3. Write a generic method to exchange the positions of two different elements in an array.
203+
204+
DONE
205+
206+
4. Write a generic method to find the maximal element in the range [begin, end) of a list.
207+
208+
DONE
209+
210+
5. How do you invoke the following method to find the first integer in a list that is relatively prime (gcd(a,b) = 1) to a list of specified integers?
211+
212+
public static <T>
213+
int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p)
214+
215+
216+
DONE
217+
218+
219+
Problems
220+
-------------------------------
221+
1. What is the following class converted to after type erasure?
222+
223+
public class Pair<K, V> {
224+
225+
public Pair(K key, V value) {
226+
this.key = key;
227+
this.value = value;
228+
}
229+
230+
public K getKey(); { return key; }
231+
public V getValue(); { return value; }
232+
233+
public void setKey(K key) { this.key = key; }
234+
public void setValue(V value) { this.value = value; }
235+
236+
private K key;
237+
private V value;
238+
}
239+
240+
Just replace both K and V with Object
241+
242+
2. What is the following method converted to after type erasure?
243+
244+
public static <T extends Comparable<T>>
245+
int findFirstGreaterThan(T[] at, T elem) {
246+
// ...
247+
}
248+
249+
it is converted to the following
250+
251+
public static Comparable
252+
int findFirstGreaterThan(Comparable[] at, Comparable elem) {
253+
// ...
254+
}
255+
256+
3. Will the following method compile? If not, why?
257+
258+
public static void print(List<? super Number> list) {
259+
for (Number n : list)
260+
System.out.print(n + " ");
261+
System.out.println();
262+
}
263+
264+
No. ? super Number allows List<Object> to be passed as a parameter to this method. The for(Number n: list) has to be changed to for(Object n: list)
265+
Another change that would make this method compilable -- change parameter type to List<? extends Number>
266+
267+
4. Will the following class compile? If not, why?
268+
269+
public class Singleton<T> {
270+
271+
public static T getInstance() {
272+
if (instance == null)
273+
instance = new Singleton<T>();
274+
275+
return instance;
276+
}
277+
278+
private static T instance = null;
279+
}
280+
281+
No, it won't. The method is static. Should have been declared public static <T> T getInstance(). The field is also static. Type parameter T is not known in static context.
282+
283+
5. Given the following classes:
284+
285+
class Shape { /* ... */ }
286+
class Circle extends Shape { /* ... */ }
287+
class Rectangle extends Shape { /* ... */ }
288+
289+
class Node<T> { /* ... */ }
290+
291+
Will the following code compile? If not, why?
292+
293+
Node<Circle> nc = new Node<>();
294+
Node<Shape> ns = nc;
295+
296+
No. Generic types are not covariant.
297+
298+
6. Consider this class:
299+
300+
class Node<T> implements Comparable<T> {
301+
public int compareTo(T obj) { /* ... */ }
302+
// ...
303+
}
304+
305+
Will the following code compile? If not, why?
306+
307+
Node<String> node = new Node<>();
308+
Comparable<String> comp = node;
309+
310+
Yes. Node<String> implements Comparable<String>
311+
312+
7. Will the following class compile? If not, why?
313+
314+
public final class Algorithm {
315+
public static T max(T x, T y) {
316+
return x > y ? x : y;
317+
}
318+
}
319+
320+
Not this class won't compile
321+
1. If T is the type parameter then the method should have been declared like
322+
public static <T> T max(T x, T y)
323+
2. Even if the method was declare correctly the binary operator ">" is not defined for classes

Java Version Specific.txt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,9 @@ Java 5 specifics
4141
@Deprecated -- to inform that the method is deprecated
4242
@Override -- to inform that this method has to override a method in a superclass. Helps to find errors.
4343
@SuppressWarnings -- to suppress warnings. E.g. warnings generated when doing potentially unsafe cast
44+
@SafeVarargs -- the implementation of the method will not improperly handle the varargs formal parameter with a type parameter
4445

45-
16. Annotation retentions policies and why they are in place?
46+
7. Annotation retentions policies and why they are in place?
4647

4748
The retention policies specify how long annotations are to retained.
4849

@@ -52,7 +53,7 @@ Java 5 specifics
5253

5354
SOURCE: Annotations are to be discarded by the compiler. (Example: @Override, @SuppressWarnings)
5455

55-
17. Suppose you would like to reuse a class in different contexts would you use annotations or external configuration? (i.e. annotation introduce dependencies).
56+
8. Suppose you would like to reuse a class in different contexts would you use annotations or external configuration? (i.e. annotation introduce dependencies).
5657

5758
Good discussion of this question can be found here
5859
http://javidjamae.com/2006/11/19/annotations-vs-xml/

README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,4 @@ java-interviews
33

44
A collection of Java interview questions and answers to them.
55
The questions were gathered all around the Internet.
6-
7-
Some answers are just copy pasted from official Java documentation, some from Stackoverflow.
8-
Most of the answers are written by the authors
6+
The answers are partly written by the commiters, partly copy-pasted from all possible sources.

0 commit comments

Comments
 (0)