Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does <> do in Java?

I know if you want a list (for example) you create it like:

List<String>

If you want to create a generic type of list you could do it like:

MyList<T>

So is the only thing <> does is to couple an object with a container or list? Does it have other uses? What does it actually do? Was reading on another post how putting static methods in generic types is a bad thing for type safety, so is this bad code?

public class LinkList<T> {

private final T t;
private final LinkList<T> next;

public LinkList(T t, LinkList<T> next){
    this.t = t;

    this.next = next;
}
// Creates list from array of T
public static <T> LinkList<T> getList(T[] t){
    if(t == null){
        return null;
    }
    LinkList linkList = null;
    for(int i = t.length-1; i >= 0; i--){
        linkList = new LinkList(t[i], linkList);
    }
    return linkList;
}

public T element() {
    return t;
}

public LinkList<T> getNext() {
    return next;
}

}

like image 270
GenericJam Avatar asked Aug 09 '12 20:08

GenericJam


1 Answers

<> helps compiler in verifying type safety.

Compiler makes sure that List<MyObj> holds objects of type MyObj at compile time instead of runtime.

Generics are mainly for the purpose of type safety at compile time. All generic information will be replaced with concrete types after compilation due to type erasure.

like image 104
kosa Avatar answered Sep 23 '22 19:09

kosa