Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cannot instantiate an object of class Integer in my code (Java)

I am creating a class, Doubly Linked List with ListNode as innerclass.

public class DoublyLinkedList<Integer> {

    /** Return a representation of this list: its values, with adjacent
     * ones separated by ", ", "[" at the beginning, and "]" at the end. <br>
     * 
     * E.g. for the list containing 6 3 8 in that order, return "[6, 3, 8]". */
    public String toString() {
        String s;

        ListNode i = new ListNode(null, null, *new Integer(0)*);

Why is it that I get the error, cannot instantiate the type Integer?

like image 378
Ha Jun Kim Avatar asked May 20 '26 00:05

Ha Jun Kim


1 Answers

The Integer in your class definition is generic type parameter which hides the Integer wrapper class.

So, new Integer(0) you use inside the class is taking Integer as type parameter, and not the Integer type itself. Since, for a type parameter T, you can't just do - new T();, because the type is generic in that class. Compiler doesn't know what type exactly it is. So, the code is not valid.

Try changing your class to:

public class DoublyLinkedList<T> {
    public String toString() {
        ListNode i = new ListNode(null, null, new Integer(0));
        return ...;
    }
}

it will work. But I suspect that you really want this. I guess you want to instantiate the type parameter inside your generic class. Well, that's not possible directly.

You pass the actual type argument while instantiating that class like this:

DoublyLinkedList<Integer> dLinkedList = new DoublyLinkedList<>();

P.S: It would be better if you explain your problem statement clearly, and put some more context into the question.

like image 173
Rohit Jain Avatar answered May 21 '26 16:05

Rohit Jain