Question

In: Computer Science

Generic types A class or interface that declares one or more generic variables is called a...

Generic types

A class or interface that declares one or more generic variables is called a generic type. In this portion of the activity, you will make a class generic.

  1. Open GenericsC.java in jGRASP then compile it.

    • At this point you should be familiar with the two type-safety warnings given by the compiler. You should be able to understand the source of the error: the use of the raw types List and Collection.

    • Since the List being declared (al) is a field of the GenericsC class, we will want to make the class itself generic in order to achieve the generality that we want.

  2. Declare a type variable for the class.

    • The class “signature” should appear as follows:
     public class GenericsC<T>
    
    • Notice how the declaration of the type variable (i.e., <T>) is placed differently for classes and interfaces than for methods. For classes and interfaces, the type variable declaration immediately follows the class name.
  3. Use this type variable as the value for the type parameter of the List field al.

    • The declaration should appear as follows:
     private List<T> al;
    
  4. Compile GenericsC.java and notice the results.

    • One warning is the same as before (unchecked call to add for the raw type Collection), but the other warning has changed. Worse, though, we now have a type error, which means our code isn’t just unsafe: It’s incorrect.

    • Let’s try to correct the new warning first (unchecked conversion of ArrayList). Since ArrayList is a generic type, we can try to provide a type value for its type variable.

  5. Use the type variable that we declared for this class as the value of the type parameter for ArrayList1. Your code should appear as follows:

     al = new ArrayList<T>();
    
  6. Compile GenericsC.java and notice the results.

    • This did indeed eliminate the type warning regarding ArrayList, but the other warning and the error remain. Let’s tackle the error now.
  7. Read the error message carefully and try to understand why al.add(o) is a problem.

     javac -Xlint:unchecked GenericsC.java
     GenericsC.java:32: error: incompatible types: Object cannot be converted to T
                 al.add(o);
                        ^
       where T is a type-variable:
         T extends Object declared in class GenericsC
     GenericsC.java:51: warning: [unchecked] unchecked call to add(E) as a member of the raw type Collection
                 c.add(i);
                      ^
       where E is a type-variable:
         E extends Object declared in interface Collection
     Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
     1 error
     1 warning
    
    • This is a typing error because al has been declared as a List with elements of type T (i.e., List<T>). Therefore, the only type of elements than can be added to al are elements of the actual type value used as the T parameter when the class is instantiated. Therefore, since o is typed as Object it can’t be added to al. Make sure you understand this.
  8. Fix this error by (1) using the parameterized type Collection<T> instead of the raw type Collection and (2) declaring o to be of type T instead of Object. Your code should appear as follows.

     public void addAll(Collection<T> c) {
         for (T o : c) {
            al.add(o);
         }
     }
    
  9. Compile GenericsC.java and confirm that this change eliminated the error.

    • Now we’re left with two warnings (Note that one is new. Why?) Both can be eliminated by using appropriate parameterized types instead of raw types in the main method.
  10. Change the declaration of c to be of an appropriate parameterized type. Your code should appear as follows:

     Collection<Integer> c = new ArrayList<Integer>();
    
    • Recompile and note that one warning has been eliminated.
  11. Change the declaration of lab to be of an appropriate parameterized type. Your code should appear as follows:

     GenericsC<Integer> lab = new GenericsC<Integer>();
    
    • Recompile and note that the final warning has been eliminated and the code is now type-safe.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
* GenericsC.java
* Used to illustrate basic principles of generic types
* and type safety in Java.
*/

////////////////////////////////////////////////
//
// Add appropriate type parameters and arguments
// to eliminate all unchecked warnings. That is,
// make this code type safe.
//
///////////////////////////////////////////////

public class GenericsC {

private List al;

/** Builds a new instance of this class. */
public GenericsC() {
al = new ArrayList();
}

/** Adds all the values in c to this object. */
public void addAll(Collection c) {
for (Object o : c) {
al.add(o);
}
}

/** Returns a string representation of this object. */
public String toString() {
StringBuilder s = new StringBuilder();
Iterator itr = al.iterator();
while (itr.hasNext()) {
s.append(itr.next());
s.append(" ");
}
return s.toString();
}

/** Drives execution. */
public static void main(String[] args) {
Collection c = new ArrayList();
for (int i = 1; i < 12; i += 2) {
c.add(i);
}

GenericsC lab = new GenericsC();
lab.addAll(c);
System.out.println(lab.toString());
}


}
Please code in java

Solutions

Expert Solution

After making the above changes, now the code looks as below.

/**
* GenericsC.java
* Used to illustrate basic principles of generic types
* and type safety in Java.
*/

////////////////////////////////////////////////
//
// Add appropriate type parameters and arguments
// to eliminate all unchecked warnings. That is,
// make this code type-safe.
//
///////////////////////////////////////////////
import java.util.*;
public class GenericsC<T>{

    private List<T> al= new ArrayList<T>();

    /** Builds a new instance of this class. */
    public GenericsC() {
    al = new ArrayList();
    }

    /** Adds all the values in c to this object. */
    public void addAll(Collection<T> c) {
    for (T o : c) {
    al.add(o);
    }
    }

    /** Returns a string representation of this object. */
    public String toString() {
    StringBuilder s = new StringBuilder();
    Iterator itr = al.iterator();
    while (itr.hasNext()) {
    s.append(itr.next());
    s.append(" ");
    }
    return s.toString();
    }

    /** Drives execution. */
public static void main(String[] args) {
    Collection<Integer> c = new ArrayList<Integer>();
    for (int i = 1; i < 12; i += 2) {
    c.add(i);
    }

    GenericsC<Integer> lab = new GenericsC<Integer>();
    lab.addAll(c);
    System.out.println(lab.toString());
}


}

This code is completely free from bugs.

Thank you! if you have any queries post it below in the comment section I will try my best to resolve your queries and I will add it to my answer if required. Please give upvote if you like it.


Related Solutions

Make the Measurable interface from Chapter 10 into a generic class. Provide a static method that...
Make the Measurable interface from Chapter 10 into a generic class. Provide a static method that returns the largest element of an ArrayList, provided that the elements are instances of Measurable. Be sure to return a value of type T. Measurable interface: public interface Measurable { double getMeasure(); } Using JAVA please
Write the definition for a generic / Template class called time that has hours and minutes...
Write the definition for a generic / Template class called time that has hours and minutes as structure. The class has the following member functions: SetTime to set the specified value in object ShowTime to display time object Sum to sum two time object & return time Write the definitions for each of the above member functions. Write main function to create three time objects. Set the value in two objects and call sum() to calculate sum and assign it...
Write the definition for a generic class called Rectangle that has data members length and width....
Write the definition for a generic class called Rectangle that has data members length and width. The class has the following member functions: setlength to set the length data member setwidth to set the width data member perimeter to calculate and return the perimeter of the rectangle area to calculate and return the area of the rectangle show to return a text to display the length and width of the rectangle sameArea that has one parameter of type Rectangle. sameArea...
Write the definition for a generic class called Rectangle that has data members length and width....
Write the definition for a generic class called Rectangle that has data members length and width. The class has the following member functions: setlength to set the length data member setwidth to set the width data member perimeter to calculate and return the perimeter of the rectangle area to calculate and return the area of the rectangle show to return a text to display the length and width of the rectangle sameArea that has one parameter of type Rectangle. sameArea...
Instructions Using the installed software for this course create a generic class called VehicleRental which accepts...
Instructions Using the installed software for this course create a generic class called VehicleRental which accepts any generic type of Vehicle ( create an instance of Car, Van and MotorCycle classes) Each type of Vehicle object has methods called drive, start and stop ( add simple print statement) The VehicleRental class has a method called rent which accept a generic type of Vehicle object, this method will call drive method of passed Vehicle object The solution will produce the following:...
The following is a Java programming question: Define a class StatePair with two generic types (Type1...
The following is a Java programming question: Define a class StatePair with two generic types (Type1 and Type2), a constructor, mutators, accessors, and a printInfo() method. Three ArrayLists have been pre-filled with StatePair data in main(): ArrayList> zipCodeState: Contains ZIP code/state abbreviation pairs ArrayList> abbrevState: Contains state abbreviation/state name pairs ArrayList> statePopulation: Contains state name/population pairs Complete main() to use an input ZIP code to retrieve the correct state abbreviation from the ArrayList zipCodeState. Then use the state abbreviation to...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to...
If a class A implements interface I1 and class C and D are derived from class...
If a class A implements interface I1 and class C and D are derived from class A, a variable of type I1 can be used to hold references of what type of objects? which one is correct 1. A, C, and D 2. A and D
For this problem you must define a simple generic interface PairInterface, and two implementations of the...
For this problem you must define a simple generic interface PairInterface, and two implementations of the interface, BasicPair and ArrayPair. a. Define a Java interface named PairInterface. A class that implements this interface allows creation of an object that holds a “pair” of objects of a specified type—these are referred to as the “first” object and the “second” object of the pair. We assume that classes implementing PairInterface provide constructors that accept as arguments the values of the pair of...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # #...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # # - meat # - to_go # - rice # - beans # - extra_meat (default: False) # - guacamole (default: False) # - cheese (default: False) # - pico (default: False) # - corn (default: False) # #The constructor should let any of these attributes be #changed when the object is instantiated. The attributes #with a default value should be optional. Both positional #and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT