Ans: Generics are a feature that allow a class to be parameterized into sub-types. Generics provide compile-time safety and prevent runtime typecasting errors resulting in ClassCastException. Without generics, a user is forced to use the lowest common base-class and then typecast the object, which is highly error-prone and has no type-safety.
Ans: Generic method are methods that is type parameterized.
public class GenericMethodExample {
public static void main(String[] s) {
String[] StrArray = new String[] { "Find", "the", "word", "in", "this",
"Array" };
System.out.println(contains(StrArray, "word"));
Integer[] intArray = new Integer[] { 4, 5, 32, 100, 303, 2002, 465 };
System.out.println(contains(intArray, 2002));
}
public static <T> boolean contains(T[] list, T itemToFind) {
for (T listItem : list) {
if (itemToFind == null) {
if (listItem == null)
return true;
} else if (itemToFind.equals(listItem)) {
return true;
}
}
return false;
}
}
Ans: Generics helps finding issues during compile time rather than runtime. Generics are parameter for types.
Ans: Generics refers to the technique of writing the code for a class without specifying the data type(s) that the class works on. It allow you to define type-safe data structures, without committing to actual data types. It allows writing less but more effective code and provides flexibility and power but the developer needs to be responsible while using it.
Ans: Generics , Enums , Autoboxing , Annotations and Static Import.
Ans: static <T extends Number> T processTheNumber(T number){
T result = number;
return result;
}
Ans: This will raise a compilation error. It is incorrect to pass a List<String> to a method accepting List<Object>. A List<Object> can accept Strings, but t1 can only accept List<Object>.
Either ls should be changed to List<Object>, or lo should be made Generic: List<? extends Object> lo
Ans: A generic type is a generic class or interface that is parameterized over types.
Ans: formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
Ans: LinkedList<Integer> l=new LinkedList<int>();
No, Generic parameters cannot be primitives.
Ans: Generics introduced in Java 1.5, facilitates strong-typing on the collection objects. Generics defines the object types that the collection can hold.
It provides compile time type-safety and ensures that only the particular type is added in collection and eliminates ClassCastException in runtime.
Ans: The Type information used for Generic objects is only available at compile time. The compiler removes all the type information when converting to byte-code. This makes the type information unavailable at Runtime and the Generic type is converted to Raw type. The compiler provides checks at compile time to prevent runtime errors for incorrect type information.
The case where things can go wrong is when directly using Raw types in the code. The compiler will raise a warning in this case but it will not fail.
Ans: Similar to regular classes and interfaces, you can create sub-types of generic classes or interfaces by extending or implementing from the generic classes or interfaces.
For example: in Java collections API, ArrayList implements List and Listimplements Collections. The sub-type relation is preserved as long as the type argument does not vary. So, ArrayList implements List and List implements Collections.
Ans: import static java.lang.System.*;
or
static import java.lang.System.*;
import static java.lang.System.*; is correct
Ans: List list = new ArrayList();
list.add("No Generics is used ");
String s = (String) list.get(0);
In the above example, ArrayList can hold any type of objects, however we need to cast each object to its appropriate data type since get method's return type is Object. A string literal is added to the list and to get it from the list we need cast and store it.
If we store an employee object for example at the first index, then the 3rd line of code will throw a run-time Exception.
List<String> list = new ArrayList<String>();
list.add("Generics is implemented");
String s = list.get(0); // no cast is required
In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.
Ans: class A<K, I extends List<K>> {
public K get(final int index, final I list) {
return list.get(idx);
}
}
class B extends A<String, LinkedList<String>> { }
Class C {
public static void main(String...args) {
A<Integer, ArrayList<Integer>> a = new A<>;
B b = new B();
A<?, ?> g;
A<? extends Integer, ?> f;
g = a;
g = b;
f = a;
}
}
Yes, this code is compile-time and run-time safe.
I and K are Generic type parameters used to ensure type safety.
The extends keyword in the first line defines the scope of the I parameter. The I parameter can only be a sub-type of List of type K. K by default extends Object.
The second extends keyword is used for inheriting class A and fixing the type parameters of A to String and LinkedList.
The get method takes an index integer and a List of type K as the parameters. It returns the list value at index, which will have a return type K because the list parameter is fixed to K.
For example, when get is called on instance b of class B, get will take a LinkedList<String> and return the String at index.
The wildcard symbols indicate that g can have any type within the bounds of the parameters. That is why a and b can be assigned to it. In the case of f, the first parameter gets limited to Integer sub-types, so only a can be assigned to it, not b. f can be assigned to g, but not the other way round.
Ans: No Java generics cannot be applied to primitive types. But you can use wrapper classes of primitive type to use Java generics.
Ans: c and d are correct.
Ans: using @SuppressWarnings("unchecked") annotation.
@SuppressWarnings("unchecked")
List<String> myList = new ArrayList();
Ans: No you cannot create instances of generic type parameters.