Thread: Generics

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Location
    Kiev, Ukrain
    Posts
    88
    Rep Power
    2

    Generics


    Starting to stady Generics.
    Hi, i got a proble with Generialized(if i can say like that) function:
    Here i have "Type mismatch: cannot convert from int to K"
    if change return type to int , the fucntion will work(same for other reult types). But i can't understand why is it wrong?:
    I got same types of return value and items.
    Code:
    	public <K extends Integer,M extends Integer> K sum(K item1, M item2){
    		K result ;
    		result = item1 + item2;
    		return result;
    	}
    And if i'm rewriting this fucntion like this:
    it doesn't works "The operator + is undefined for the argument type(s) K, M"
    So i can't use generics in it's original way , i think .
    Means it is imposible for me to write sum function for all of the types .
    Code:
    	public <K extends Number,M extends Number> float sum(K item1, M item2){
    		float result ;
    		result = item1 + item2;
    		return result;
    	}
    Last edited by FAQer; December 17th, 2013 at 12:08 PM.
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,021
    Rep Power
    1285
    In your first method, the return type is K. The + operator will convert the operands to int. So you need to cast the result to K. This will give you a compiler warning. You can suppress it by putting @SuppressWarnings("unchecked") before the method.

IMN logo majestic logo threadwatch logo seochat tools logo