(Lab-02l) Writing Generic Methods and Classes
(Lab-02l) Writing Generic Methods and Classes
Fall 2022
Week-2 Manual
Writing Generic Methods and Classes
v1.0
3/23/2019
Week-2 Manual 2022
Page 1
Week-2 Manual 2022
Page 2
Week-2 Manual 2022
Example
Following example illustrates how extends is used in a general sense to mean either "extends" (as
in classes) or "implements" (as in interfaces). This is an example which takes two generic
arguments and return true if the numbers are equal, otherwise returns false.
Page 3
Week-3 Manual 2022
public T getValue() {
return this.value;
}//Getter
//Printing Values
System.out.println("Integer Value: " +
integerBox.getValue());
System.out.println("String Value: " +
stringBox.getValue());
}//main
}//class
NOTE: Open the Box.java code from the Code folder. Compile and run the code.
Page 4
Week-3 Manual 2022
private T obj1;
private T obj2;
//Constructor
public GenericClassLab1(T obj1, T obj2) {
}//GenericClass
//Setters
public void setObj1(T obj1) {
}//Set Obj1
//Getters
public T getObj1() {
}//get Obj1
public T getObj2() {
}//get Obj2
Page 5
Week-3 Manual 2022
Example:
class Maps<K,V>{
private K key;
private V value;
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public String toString() {
return "Maps [key=" + key + ", value=" + value + "]";
}
NOTE: Copy the code and complete all the remaining steps. Create new Maps object and
run the code in a new file RunMaps.java.
Page 6
Week-3 Manual 2022
In this task you are being asked to use the class Maps created in previous program.
Create an array of type Maps and add multiple Maps in it.
Maps[] mapArray = new Maps[];
The ArrayList class is a resizable array, which can be found in the java.util package.
The difference between a built-in array and an ArrayList in Java is that the size of an array cannot
be modified (if you want to add or remove elements to/from an array, you have to create a new
one). While elements can be added and removed from an ArrayList whenever you want. The
syntax is also slightly different:
import java.util.ArrayList;
Perform the same task using ArrayList of type Maps and create a new method that will print all the
Maps inside the ArrayList.
Page 7
Week-3 Manual 2022
Page 8
Week-3 Manual 2022
In this task, you are being asked to create three arrays using Wrapper classes of Integer, Double
and String respectively.
• Print all of them using one generic method printArray. You can use the following header.
public static <T> void printArray(T[] a)
• Now create a search method that will take the key value and returns the index of the value if
present and -1 if not.
You can use the following header for reference:
public static <T> int search(T[] a, T key)
• Perform the same task using Linear search and with Binary Search as well.
Page 9