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;
}
}
<>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With