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
1. create a class called ArrayStack that is a generic class. Create a main program to...
1. create a class called ArrayStack that is a generic class. Create a main program to read in one input file and print out the file in reverse order by pushing each item on the stack and popping each item off to print it. The two input files are: tinyTale.txt and numbers.txt. Rules: You cannot inherit the StackofStrings class. 2. Using your new ArrayStack, create a new class called RArrayStack. To do this, you need a) remove the capacity parameter...
Write a class "LinkedBag" which implements this interface. The LinkedBag class has two instance variables firstNode...
Write a class "LinkedBag" which implements this interface. The LinkedBag class has two instance variables firstNode and numberOfEntries. It has an inner class Node. BagInterface.java /** An interface that describes the operations of a bag of objects. @author Frank M. Carrano @author Timothy M. Henry @version 4.1*/public interface BagInterface<T>{ /** Gets the current number of entries in this bag. @return The integer number of entries currently in the bag. */ public int getCurrentSize(); /** Sees whether this bag is empty....
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...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT