tags:

views:

87

answers:

2

I'm coming from a c# background, how do generics look in java compared to c#? (basic usage)

+5  A: 

That's a pretty huge question, to be honest - the biggest differences aren't in syntax, but in behaviour... at which point they're really, really different.

I would suggest you read through the Sun generics tutorial and Angelika Langer's Java Generics FAQ. Forget everything you know about generics from C#/.NET first though. In particular, while .NET generic types retain the type argument at execution time, Java generics don't due to type erasure.

So in other words, in C# you can write:

public class GenericType<T>
{
    public void DisplayType()
    {
        Console.WriteLine(typeof(T));
    } 
}

... you can't do this in Java :(

Additionally, .NET generics can have value type type arguments, whereas Java generics can't (so you have to use List<Integer> instead of List<int> for example).

Those are probably the two biggest differences, but it's well worth trying to learn Java generics from scratch instead of as a "diff" from C#.

Jon Skeet
+1  A: 

There are a number of articles about this, but there's one notable example that discusses some of the differences and limitations of generics in Java.

Here is a simple example taken from the existing Collections tutorial:

// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
      if (((String) i.next()).length() == 4)
        i.remove();
}

Here is the same example modified to use generics:

// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); )
      if (i.next().length() == 4)
        i.remove();
}
Ed Altorfer