View RSS Feed

My Java Tips

Method parameters bounded by a Class

Rate this Entry
by , 11-09-2011 at 06:45 PM (640 Views)
Java Generics are introduced in Java 5.0 and have introduced new exciting ways to code. In this post, I will show you how you can use generic types for method parameters.


Lets take an example: You have Integer, Float, BigInteger and Double values and want to compare them using user made functions.
You have to write separate functions for comparing Integer with BigInteger, Integer with Double, Integer with Float and so on. But there is an easy way to it. Simply use generics.

java.lang.Number class has following subclasses:
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short

So, we can use as a bound for our method, so it can accept parameters of Integer, Float, Double and BigInteger. Following will be the signature of our method:

Java Code:
public static  void compareValues (T value1, T value2)
compareValues method takes 2 parameters of bound T. What is T? T can be any class that extends the class Number which are: BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short. So compareValues can take parameters of following type:
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short

Example below has a very flexible method called compareValue that is the main focus:

Java Code:
Integer i = new Integer(19);
Float f = new Float(16.8f);
compareValues(i,f);
Double d = new Double(18.22);
BigInteger bi = new BigInteger("18");
compareValues(d,bi);


public static  void compareValues(T value1, T value2){

System.out.println("Comparing int values of " + value1 + " of type " + value1.getClass() +
    " with " + value2 + " of type " + value2.getClass());
if(value1.intValue() == value2.intValue())
System.out.println("Equal");
else
System.out.println("Not Equal");
}
Output:


Comparing int values of 19 of type class java.lang.Integer
with 16.8 of type class java.lang.Float
Not Equal
Comparing int values of 18.22 of type class java.lang.Double
with 18 of type class java.math.BigInteger
Equal

This is just an example to introduce generic types. What if I try to send a String value as a parameter to compareValue? Compiler will show Bound mismatch error.

Submit "Method parameters bounded by a Class" to Facebook Submit "Method parameters bounded by a Class" to Digg Submit "Method parameters bounded by a Class" to del.icio.us Submit "Method parameters bounded by a Class" to StumbleUpon Submit "Method parameters bounded by a Class" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments