I need someone to just write this out the way it is supposed to be so I have an
ID: 3824250 • Letter: I
Question
I need someone to just write this out the way it is supposed to be so I have an answer key; Thanks.
Introduction
Java is a strongly typed language, meaning that the compiler and JVM enforce proper matching of the type of data in use. Recall that we cannot even assign a long variable to an int variable without causing a "type mismatch" syntax error.
Generics allow us to abstract over data types. The ArrayList class from the java.util package yields a data structure that is an abstract data type (ADT) . Look at its code definition here. We can easily declare an ArrayList of String, Integer, Double, or some other object. This "multipurpose use" is precisely the beauty of a generic class. Without this we would (and have) made separate arrays and methods to hold and manipulate each data type.
For your first foray into generics, you will study two simple classes from the interface for the Couple class. This class has two members (thus a "couple"). The members are of type T.
Task 1
You will implement a generic version of the Couple class.
The following code is an ADT for two String members. To convert this ADT to a generic Couple, you will introduce a type parameter T. This parameter can be thought of as a variable for which one can substitute a (reference) type. You will need to:
use the Diamond <T> after the class name
replace String with T everywhere else
use the member object's toString() method within the Couple.toString() method to access
its value. (Recall that every Java object inherits from Object, so a toString() method is available.)
class Couple of two Strings:
// An ADT for Two strings
class Couple { // fields
private String first; private String second;
// constructor Couple(String f, String s) {
}
String getFirst() { return first;
return second; void setFirst(String f) {
first = f;
void setSecond(String s) {
second = s;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
}
Now add one more method to the Couple class. Creating an equals() method requires some thought. We don't want to compare the object references but the members first and second in one object to first and second in the other object. We need a boolean method to which we pass in the object whose member variables should be compared to this object's members. The complication arises when we try to compare our Couple-of-anything ADT to another Couple-of- anything ADT. Our first attempt might be:
public boolean equals(Object otherObj){ boolean isEqual = false;
Couple<T> o = null;
if (otherObj instanceof Couple<T>) {
isEqual = (this.first.equals(o.first) && (this.second.equals(o.second)); }
}
Adding this to Couple.java, we find it does not compile. How very sad. The problem is that the instanceof operator does not work on parameterized types. Instead we can call the getClass() method (ask yourself where this method is defined) on both this and otherObj then compare the
}
}
returned values. (Did you answer that getClass() is inherited from Object? Good job!). So now our next attempt might be:
public boolean equals(Object otherObj){
boolean isEqual = false;
Couple<T> o = null;
if (this.getClass() == otherObj.getClass()) {
isEqual = (this.first.equals(o.first) && (this.second.equals(o.second)); }
}
This survived the compile process, but there is a warning that our program has used an unsafe operation. Eclipse reports, "Type safety: unchecked cast from Object to Couple<T>". The problem is with this line: o = (Couple<T>) otherObj;
Even though we will check the class in the if condition, the compiler is not able to prove that a ClassCastException will not be thrown, so it provides a warning. What to do? Nothing for it but to suppress the warning by adding an annotation (a note to the compiler, like we do with @override).
isEqual = (this.first.equals(o.first) && (this.second.equals(o.second)); }
}
Now you are ready to run the driver class. Yay!
Task 2
Load the CoupleClient class that exercises the generic Couple class. Your code will read in data from a file given in the command line.
If the file name is not given, the program should terminate after displaying the message: Usage: java CoupleClient inputFileName
If the file cannot be opened, the program should terminate after displaying the message: File not found
The text file will contain a pair of elements per line. An example of input cc2.txt:
Your program should be able to use these constructs:
Using the generic Couple, a Couple of Strings can be created as follows:
Using the generic Couple, a Couple of Doubles can be created as follows:
Couple<Double> cd = new Couple<Double>(new Double(3.14), new Double(12.34));
But since boxing can occur automatically, this equivalently can be coded as:
Printing a Couple System.out.println(cs) will output: (sun, moon)
After using cs.setSecond("light"), then System.out.println(cs) will output: (sun, light)
Your class will be tested with my client driver program. Here is a sample of a test run:
> java CoupleClient input.txt (day, night)
(6.0, 12.0)
(moonlit, night)
At this point you should begin to have a feel for structure and syntax of generic types.
Task 3
Write a program Prog7a.java that has the following generic methods.
1. Write the following method that returns a new ArrayList. The new list contains the nonduplicate
(i.e., distinct) elements from the original list.
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list)
2. Write the following method that shuffles an ArrayList:
3. Write the following method that returns the largest element in an ArrayList:
4. Write the following main method that tests the above methods. (Use ArrayList’s implicit toString() to print. This gives the brackets.)
Example runs:
I 6 7 5 3 1 -1 -2
Maximum: bab
Task 4
Write a program Prog7b.java that has the following generic methods.:
1.
2.
3.
4.
Implement the following generic method for linear search.
Implement the following method that returns the maximum element in an array:
Implement a generic method that prints the array contents inside brackets and separated by comma and a space. (This mimics the ArrayList’s toString() method.)
Write the following main method that tests the above methods.
o Read in data type for the array: S for String, D for Double, or I for Integer o Read n number of elements in the array list.
o Read in n elements to initialize array list.
o Read in k key value to search for in list.
o Printlist.
o Call linearSearch(list, k) and print the result: o Call max(list) and print the result:
Example runs:
> java CoupleClient input.txt (day, night)
(6.0, 12.0)
(moonlit, night)
(6.0, -12.34) ((moonlit, night), (one, Couple)) cs equals cd: false cs equals cs2: false cs equals cs3: false cs equals ccs: false cs equals ccs.first: true cs equals ccs.second: false one moonlit nightCS 108 Programming Assignment 7 Objectives 1) Develop an application that uses generic methods. 2) Explore how a list structure is manipulated. 3) Use object-oriented design. 4) Employ the Comparable interface to compare objects. 5) Introduce type erasure. Background Reading Zy Books 15. Generics Begin here (truly) -httglldocs oracle somliavaseltutorialliavalgenerics index html The first 3 to 5 sections are enough. The things you will want to get definitions for formal parameters, generic class, type parameters, type parameter naming conventions, parameterized types, raw types, unchecked error messages, generic methods. lf you want to go on, look at type Introduction Java is a strongly typed language, meaning that the compiler and JVM enforce proper matching of the type of data in use. Recall that we cannot even assign a long variable to an int variable without causing a "type mismatch" syntax error. Generics allow us to abstract over data types. The Arraytist class from the java.util package yields a data structure that is an abstract data type (ADT). Look at its code definition here. We can easily declare an ArrayList of String, Integer, Double, or some other object. This "multipurpose use is precisely the beauty of a generic class. Without this we would (and have) made separate arrays and methods to hold and manipulate each data type. For your first foray into generics, you will study two simple classes from the interface for the Couple class. This class has two members (thus a "couple"). The members are oftype r. Task 1 You will implement a generic version of the couple class. The following code is an ADT for two String members. To convert this ADT to a generic Couple, you will introduce a type parameter T.This parameter can be thought of as a variable for which one can substitute a (reference) type. You will need to: use the Diamond T after the class name replace String with everywhere else use the member object's tostring0 method within the couple.tostring method to access its value. (Recall that every Java object inherits from object, so a toString0 method is available.)
Explanation / Answer
class Couple<T> { // fields
private T first; private T second;
// constructor
Couple(T f, T s) {
first = f;
second = s;
}
// getters and setters
T getFirst() {
return first;
}
T getSecond() {
return second;
}
void setFirst(T f) {
first = f;
}
void setSecond(T s) {
second = s;
}
// override an Object method
public String toString() {
return "(" + first.toString() + ", " + second.toString() + ")";
}
@SuppressWarnings("unchecked")
public boolean equals(Object otherObj){
boolean isEqual = false;
Couple<T> o = null;
if (this.getClass() == otherObj.getClass()) {
o = (Couple<T>) otherObj;
isEqual = (this.first.equals(o.first) && (this.second.equals(o.second)));
}
return isEqual;
}
}
-----------------------------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CoupleClient
{
public static void main(String args[])
{
if(args.length!=0)
{
try
{
Scanner read=new Scanner(new File(args[0]));
Couple<String> cs = new Couple<String>(read.next(), read.next());
Couple<Double> cd = new Couple<Double>(read.nextDouble(), read.nextDouble());
System.out.println(cs);
System.out.println(cd);
System.out.println(cs.equals(cd));
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
}
else
{
System.out.println("java CoupleClient inputFileName");
}
}
}