Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a hard time with generic classes and generic methods in java

Tags:

java

generics

New to java, I did search for examples, but I'm having a really hard time.

I have a node class that uses generics:

public class Node<T> {

    private int key;
    private T data;
    private Node<T> nextNode;

}

The node is Okay.

public class GenericDictionary implements GenericDictionary_interface {

    private int capacity;
    private Node<T> [] slots;

    public void add (Node<T> newNode) {

    }
}

This is how I would write it, I think. I want the GenericDictionary to work with node objects.

I get an error: "T cannot be resolved as a Type".

Thing is I don't know how it should look like.

like image 441
Kalec Avatar asked May 03 '26 16:05

Kalec


2 Answers

Your GenericDictionary class would need to be generic as well:

public class GenericDictionary<T> ...
{
}

At that point, it'll be fine to use Node<T> within the class.

If the interface contains the add method, the interface should probably be generic too:

public class GenericDictionary<T> implements Dictionary<T>
{
}

I'd advise against an interface called GenericDictionary_interface, by the way... if there's only ever going to be one implementation, you could call the interface GenericDictionary and the implementation GenericDictionaryImpl - somewhat horrible, but reasonably common. If there are multiple implementations, name the implementation by some differentiating aspect.

like image 116
Jon Skeet Avatar answered May 06 '26 05:05

Jon Skeet


In your second one it doesn't have any idea what type T is so you need to add it to the declaration

public class GenericDictionary<T> implements GenericDictionary_interface {

private int capacity;
private Node<T> [] slot;

public void add (Node newNode) {

}

}

like image 20
awright18 Avatar answered May 06 '26 06:05

awright18



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!