Bounded Type Generics

2 0 0
                                    

Bounded Type is when you want to restrict the type parameter of a generic. So, to restrict a parameter type in generics, you use the extends keyword like in class. Note that operators such as greater than(>) and more cannot be used in your generic class since the operators is only defined in the primitive types but you can use the standard functional interface as a substitute for those operators like compare() method of a Comparable <T> interface.

=================

import java.util.ArrayList;
import java.util.List;
class Generic070122 {
private <T extends Number, V> boolean compare(Pair<T, V> p1, Pair<T, V> p2){
return p1.getT().equals(p2.getT()) && p1.getV().equals(p2.getV());
}
private <T extends Comparable<T>, V> int comparingList(List<Pair<T, V>> list, Pair<T, V> elem){
int ctr = 0;
for(Pair<T, V> e: list){
if(e.getT().compareTo(elem.getT()) > 0){
++ctr;
}
}
return ctr;
}

public static void main(String[] args) {
Generic070122 yourClass = new Generic070122();
Pair<Double, String> pair1 = new Pair<>(5.0, "apple");
Pair<Double, String> pair2 = new Pair<>(5.0, "apple");
Pair<Double, String> pair3 = new Pair<>(1.0, "orange");
Pair<Double, String> pair4 = new Pair<>(10.0, "orange");

boolean b1 = yourClass.compare(pair1, pair2);
System.out.println("Equality: " + b1);

List<Pair<Double, String>> pairList = new ArrayList<>();
pairList.add(pair1);
pairList.add(pair2);
pairList.add(pair3);
pairList.add(pair4);
System.out.println("how many doubles greater than three: " +
yourClass.comparingList(pairList, new Pair<>(3.0, "")));
}
}
class Pair<T, V>{
private T t;
private V v;

Pair(T t, V v){
this.t = t;
this.v = v;
}

protected T getT(){
return t;
}
protected V getV(){
return v;
}
}

=================

Result:

Equality: truehow many doubles greater than three: 3

Java ProgrammingWhere stories live. Discover now