Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use primitive types for generic parameters in a class or method?

Tags:

java

I am writing a short paper on generics and I have not really used them all that much in Java. I was wondering if a primitive type can be used as a parameter type in a generic variable. I have not been able to get it to compile with a generic parameter that is of a generic type.

Question: I am somewhat not certain as to how generics can handle primitive datatypes. Can someone example how I would have to declare the method different to not have to add a cast to the int type with Integer and if it is possible to use a primitive Java datatype in the class declaration

   DDHGeneric<int,int,int,int> t = new DDHGeneric<int,int,int,int>();

Is there a way to do this?

The following declaration does not compile either. I do know that from what I know about generics that there is a different between using the primitive data types and a user-defined class.

   DDHGeneric<int, int, int, int> temp2 = new  DDHGeneric<int, int, int, int>();

Class:

public class DDHGeneric<T,K,Bigfoot,Pizza> {
    T a;
    K n;
    Bigfoot u;

    public DDHGeneric() {
    }

    private <rapper> void myMethod(rapper y) {
    int temp = y; <--Errors out on this line as will.
}

    public <Pizza> void myAddition(Pizza a, Pizza b) {
    }

    private <K> void me(K a, K b, K c) {
    }

    public static void main(String[] args) {
         DDHGeneric<int, Integer, Integer, Integer> temp = new  DDHGeneric<int, Integer, Integer, Integer>();
         temp.myAddition(5, 4);
         temp.a = "Test this string!" ;
    }
}
like image 685
Doug Hauf Avatar asked Nov 17 '25 22:11

Doug Hauf


1 Answers

You cannot.

Oracle gives an article on this topic.

to quote:

When creating a Pair object, you cannot substitute a primitive type for the type parameter K or V:

Pair<int, char> p = new Pair<>(8, 'a'); // compile-time error

You can substitute only non-primitive types for the type parameters K and V:

Pair<Integer, Character> p = new Pair<>(8, 'a');

like image 166
Kyle Falconer Avatar answered Nov 20 '25 12:11

Kyle Falconer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!