lab6 - generics

lab6 - generics - Page 1 of 4 Lab 6: Generics Exercise 1:...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Page 1 of 4 Lab 6: Generics Exercise 1: Generics Example: The following code defines a generic class to describe pairs of objects. a. Add code to define two mutator methods setFirst and setSecond . Each method should be void. Compile your code. Pair.java public class Pair<T,S> { private T first; private S second; // instance variables public Pair (T firstElement, S secondElement) // constructor { first = firstElement; second = secondElement; } public T getFirst() { return first; } // accessors public S getSecond() { return second; } // 1. Define the two mutators here. public void setFirst(T newFirst) { first = newFirst; } // mutators public void setSecond(S newSecond) { second = newSecond; } } // end of generic class Pair b. Now that we have a class for handling general pairs of objects, we need a program to demonstrate it working. Compile and run the following demo program. PairDemo.java import java.util.*; public class PairDemo { public static void main(String args) { Pair<String,String> famousCouple = new Pair<String,String>("Romeo", "Juliet"); System.out.println("\nThe prince is named: " + famousCouple.getFirst() ); System.out.println("The princess is named: " + famousCouple.getSecond() ); } // end of main method } // end of class Exercise 2: Trivial Pursuit. Let's teach the computer how to play trivial pursuit. Add a few pairs in which the first element is the country and the second is its capital as shown below. Add at least two pairs of your own. as shown below....
View Full Document

Page1 / 4

lab6 - generics - Page 1 of 4 Lab 6: Generics Exercise 1:...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online