Danielle
Danielle

Reputation: 243

When to create a generic class

I haven't used generics before and I am wondering when I should use them and what the advantages are. I think it might be appropriate for a collection that I made since java always uses generics for collections as well but if I call the methods I created the type is already set in the function so it would give an error anyway. When should I use a generic class? Could you give an example because I am not sure how to use it. At the moment my code is as follows:

public class NodeList {
  private static final int MAX_AMOUNT_OF_NODES = 12;
  private HashMap<String, Node> nodeList;

  public NodeList(){
    nodeList    = new HashMap<String, Node>(MAX_AMOUNT_OF_NODES);
  }

  public Node get(String id){
    return nodeList.get(id);
  }

  public boolean add(Node node){
    if(nodeList.size() <= MAX_AMOUNT_OF_NODES){
      nodeList.put(node.id, node);
      return true;
    }
    return false;
  }
}

Upvotes: 1

Views: 322

Answers (4)

hvgotcodes
hvgotcodes

Reputation: 120178

You can look at the existing API for guidance. For example, all the Collections are generic. That is because all collections contain elements of a type.

From that, it makes sense that generic classes should be used when you would have to create the exact same code again and again for different types. If you have to do that, generics might offer you some benefit.

As far as an example, the docs are a good place to start.

From that link, the first code sample is

public class Box<T> {

    // T stands for "Type"
    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

Conceptually, there is a Box class that is going to contain something. What it contains does not matter, because the type is specific by the programmer. A Box instance can contain basically anything. When the programmer needs to create a box, he/she specifies the type.

Box<SomeClass> myBox = new Box<SomeClass>();

Think about it this way -- if you wanted to create a general Box that could hold anything without generics, you would have to

1) have the field f be an Object, or
2) create a Box class for every type a box could contain.

With generics, you only need one class, and you can specify the exact type. Maybe if you are doing something and your approach involved either 1 or 2 above, it's better to use generics.

Upvotes: 2

Panos
Panos

Reputation: 31

Generics are a way for Java to force a collection data structure (HashMap in your case) to accept only a specific types of objects. This means that at compile time, if you tried something like:

nodeList.add(1, new Node());

it would fail and not compile since 1 is not a String object. It is generally a way to write tidier code.

Check this link as well:http://en.wikipedia.org/wiki/Generics_in_Java

Upvotes: 0

Shivan Dragon
Shivan Dragon

Reputation: 15219

You can generically type the methods arguments as well as the class itself. Here's an example from Java's java.util.List interface:

public interface List<E> {

//...

    boolean add(E e);

//...

}

Upvotes: 0

Mark Peters
Mark Peters

Reputation: 81074

If Node is a class that can hold a piece of data with certain type (like String, for example) then you should generify Node and subsequently NodeList to prevent type errors.

If you don't, then you leave it up to the user of your NodeList to ensure that she never adds an Integer when the list is only supposed to hold Strings. Generics is primarily about catching type problems at compile time rather than runtime.

It's pretty simple to do so, change something like this:

public class Node {
    Object data;
    //...
}

to something like this:

public class Node<T> {
    T data;
    //...
}

public class NodeList<T> {
    public Node<T> get(String id) {
        //...
    }

    public boolean add(Node<T> node) {
        //...
    }
}

Your NodeList looks like it could potentially have a second type parameter for the key type, which right now you're constraining to String.

Upvotes: 1

Related Questions