Question: Exercise 2 : Java Wildcards In a new program write a method printList that takes a List of any type and prints each element in

Exercise 2: Java Wildcards
In a new program write a method printList that takes a List of any type and prints each element in the list. Use wildcards to achieve this.
Hints:
Wildcards: Use wildcards (?) to write more flexible code that can work with any subtype of a given class. Remember, ? extends T is bounded wildcard for subtypes of T, and ? super T is for supertypes of T.
Use Case for Wildcards: Use wildcards when you need to process data from a collection but don't need to add new data to the collection or when the operation is read-only.
Upper Bounded Wildcard Example: If you have a method that needs to read a list of numbers and calculate their sum, use List as the method parameter. This allows the method to work with a list of Integer, Double, or any other type that extends Number.
Lower Bounded Wildcard Example: If you have a method that needs to add integers to a list, use List as the method parameter. This ensures that you can pass a list of Integer or a list of any superclass of Integer (like Number or Object).
Avoid Wildcards for Return Types: Generally, avoid using wildcards in return types because they can make the method's return type more difficult to work with. Instead, use specific types or generic type parameters.
Exercise 3: Java ArrayList
In a new program, create an ArrayList of 8 strings. After creating the ArrayList, do the following:
add 2 elements to it
modify an element
print all elements
remove an element by index
remove an element by string value
ArrayList: Utilize add(), get(), set(), remove(), and size() methods for managing elements.
Importing ArrayList: Ensure you import the java.util.ArrayList package at the beginning of your Java program.
Looping Through an ArrayList: You can use a standard for loop, an enhanced for loop, or an iterator to loop through an ArrayList. When using a standard for loop, use the size() method for setting the loop's condition.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!