Write a main() in a class called Explore that declares two different java.util.L
ID: 3675361 • Letter: W
Question
Write a main() in a class called Explore that declares two different java.util.LinkedList objects. Make one's generic type String and the other's type Integer. Add a bunch of different String object to one and a bunch of Integer (wrapper class for int) objects to the other. Use the method that returns an Iterator for a LinkedList and then write a while loop that used the hasNext() and next() methods of the iterator to display all the values for one of the lists. Next, use the Java for-each statement with the other list to display all of the values in it without explicitly using hasNext(), next(), and certainly not the get() method of the list as that would be grossly inefficient .
Explanation / Answer
Hi for your reference i have written the code that explains the concept for your understanding,
Let's return to the MyArrayList example. With the use of generics, we can write our program as follows:
Dissecting the Program
MyGenericArrayList<E> declare a generics class with a formal type parameter <E>. During an actual invocation, e.g., MyGenericArrayList<String>, a specific type <String>, or actual type parameter, replaced the formal type parameter <E>.
Behind the scene, generics are implemented by the Java compiler as a front-end conversion called erasure, which translates or rewrites code that uses generics into non-generic code (to ensure backward compatibility). This conversion erases all generic type information. For example, ArrayList <Integer> will become ArrayList. The formal type parameter, such as <E>, are replaced by Object by default (or by the upper bound of the type). When the resulting code is not type correct, the compiler insert a type casting operator.
Hence, the translated code is as follows:
When the class is instantiated with an actual type parameter, e.g. MyGenericArrayList<String>, the compiler ensures add(E e) operates on only String type. It also inserts the proper downcasting operator to match the return type E of get(). For example,
With generics, the compiler is able to perform type checking during compilation and ensure type safety at runtime.
Unlike "template" in C++, which creates a new type for each specific parameterized type, in Java, a generics class is only compiled once, and there is only one single class file which is used to create instances for all the specific types.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.