My goal is to simply take my int and interpret it as an Integer trough any means, no work-arounds
I have an object Node<T> (int Key, T value).
I am working towards a program that can properly use generics, for now I just want it to use integers. However I can’t make Node<int>, I have to use Node<Integer>.
I don’t know how to read an Integer from the console, I know how to read only int.
code
public void addNumber (int number) {
Node<Integer> newNode = new Node<Integer>(number,(Integer)number); //does not work
this.gd.add(newNode);
}
What I tried:
Integer iNumb = new Integer(number); // Could not instantiate the type integer
and:
Node<Integer> newNode = new Node<Integer>(number, number);
I have no constructor for this, going that route would be pointless.
I’ve also tried this:
public void addNumber() throws GenericDictionary_exception {
Scanner input = new Scanner(System.in);
int number;
System.out.print("Number: ");
if (input.hasNextInt()) {
number = input.nextInt();
} else
throw new GenericDictionary_exception(
"Error\n\t**This version only supports input of numbers**");
Integer integer = number; // Type missmatch
}
How do I take an int and cast it to Integer if generics are in play in Java?
int num = 5;
Integer integer = num;
That works.
Assuming number is an int:
Java generics have some limitations, and one of them is that you can’t use primitives, you must instead use Java’s primitive wrapper classes.
Here’s a more involved explanation:
Why don't Java Generics support primitive types?
EDIT:
Just to be clear, I assume your Node class looks something like this:
My suggestion would be to try compiling and running this test code. If it doesn’t work, then there’s something wrong with your environment. If it does work, the problem may be something to do with your code that we’re not seeing.
EDIT 2:
This worked for me. Again, I’d suggest trying it as a standalone program: