6

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;
}

}

GenericJam
  • 2,915
  • 5
  • 31
  • 33
  • It specifies a type parameter. You can read more on generics [here, in the relevant Java Tutorial](http://docs.oracle.com/javase/tutorial/extra/generics/simple.html). – obataku Aug 09 '12 at 20:43
  • So... is this bad code because of the static method in a generic type? What are the potential dangers of having it there? Is the problem that I could jam more than one type into the list or would that give me a compile error? – GenericJam Aug 09 '12 at 20:51
  • 1
    Duplicate of http://stackoverflow.com/questions/31693/what-are-the-differences-between-generics-in-c-sharp-and-java-and-templates-i ? – Aaron Kurtzhals Aug 09 '12 at 20:53
  • @GenericJam I see nothing at all wrong with using static methods in generic types. I do see something wrong in your `getList` implementation, though, since it merely returns a `LinkList` whose element is the last in the array and whose adjacent neighbor is null. – obataku Aug 09 '12 at 20:54
  • @AaronKurtzhals The first answer in that post does an excellent job of explaining generics but I also wanted to know why it is dangerous(?) to have a static method in a generic type. You have to trick the compiler to not complain by putting '' after static or is it casting? I don't fully understand why it works. – GenericJam Aug 09 '12 at 21:08

4 Answers4

11

<> 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.

kosa
  • 65,990
  • 13
  • 130
  • 167
6

When you put <> and a type inside, it is used in order to convert what would be a potential runtime exception, into a compilation error.

Take this code for example, without generics

ArrayList stringList = new ArrayList();
stringList.add("string");
stringList.add(3.4);
String s = (String) stringList.get(1);

// THIS WOULD COMPILE AND PRODUCE A RUNTIME ERROR, COMPARING String TO double.

If you add generics, you could could find these bugs when writing it.

consider the following code:

ArrayList<String> stringList = new ArrayList<String>(); // Since Java 7 you can write - new ArrayList<>()
stringList.add("string"); // OK
stringList.add(3.4); // Would not compile!

This way you can catch type-related errors in compile time.

The compiler itself doesn't care whether or not you used generics. it removes all of them on compilation and acts as if you didn't used generics. however, it won't let you compile if you have a compilation error in the first place.

I also noticed I didn't answered your question about the code.

When you do something like this

class LinkedList<T> {
....
.... 
}

You tell the compiler that this class supports generics, and in that case it is possible to do what I've said above

you could do

LinkedList<String> list = new LinkedList<String>();

Now, where ever in your class it says T it would acts as if it says String, thus allowing only adding and mainpulating Strings.

La bla bla
  • 8,558
  • 13
  • 60
  • 109
  • You sure about that runtime error? I thought it'd just return `false`...in fact, i thought that was part of the `equals` contract, that comparing to a different-typed object just returns `false`. – cHao Aug 09 '12 at 20:47
  • This is a good example of how generics work. It should also be noted that generics are not limited to containers. These just happen to be the most common use of generics. – Code-Apprentice Aug 09 '12 at 20:48
3

<> is used for a cool feature called generics.

Before Java 5, generics did not exist. Collections like ArrayList returned and manipulated Objects. The problem with this is when you know that you will only store Strings, for example. But if you are working with Objects in all your classes, not only do you have to use annoying casting (String blah = (String) list.get(9);), but if you make an error and put an Integer in your list, your program will ClassCastException and burn.

Java 5 solved this with generics, so now you can say ArrayList<String> to say that you will only use Strings in this ArrayList. But what if you need to make ArrayList<Supercalifragilisticexpealidocious>? Obviously, typing that is not a pleasant experience, especially when you have to type

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<Supercalifragilisticexpealidocious>();

to declare one of these. Moreover, it could lead to typos, especially with a type parameter this size; at some point, you are bound to mistype a letter or two and make your program cannot find symbol and burn--or worse, silently use the wrong class and cause logic errors.

Java 7 introduces the plain <> syntax. It is called the diamond operator and makes it so you don't have to retype the type parameter (the thing inside the <>) on the right side of the assignment operator. Therefore,

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<Supercalifragilisticexpealidocious>();

becomes

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<>();

which means a lot less time retyping Supercalifragilisticexpealidocious.

Hope this helps!

ameed
  • 1,132
  • 6
  • 25
1

<> can be used with any class you wish, not just containers. These are simply the most common since we want to be able to store any kind of Object we want in a container and still keep type safety. To understand this in more depth, you should research generics and what they are used for.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268