-4

I have a doubt about generic programming in Java.

When C++ compiler founds a reference to a generic function/object (templates) inside the code, it creates a function with the non-generic (concrete) type used (for any type it meet).

I don't know how it works in Java. javac behaviour is the same as the C++ compiler? Or it is managed by JVM at runtime?

Thank you

Pierpaolo Cira
  • 1,457
  • 17
  • 23
  • 3
    Java has type erasure. http://docs.oracle.com/javase/tutorial/java/generics/erasure.html – Cruncher Oct 31 '13 at 12:47
  • Java uses the most general concrete type that it can safely use. It's often Object, unless some kind of requirement is put on what types can be used – Cruncher Oct 31 '13 at 12:48

2 Answers2

3

Generics in Java are purely a compile time construct to ensure type safety - they're erased by the compiler and replaced by the raw equivalent (but guaranteed safe unless you've specifically casted to void that type safety.)

This is a relatively neat way of implementing generics, since no modifications need to be done to the VM or hotspot - just the compiler. As well as the obvious limitation that there's no generic type information available at runtime, it does occasionally pose the limitation that the "generic-free" instance has to make sense also. For instance if I want to do something like:

public class CompareMe implements Comparator<Thing>, Comparator<OtherThing> {

    public int compareTo(Thing other) {
        //Blah
    }

    public int compareTo(OtherThing other) {
        //Blah
    }
}

...then that's not possible using that form, since the direct generic-free equivalent would be:

public class CompareMe implements Comparator, Comparator {

    public int compareTo(Object other) {
        //Blah
    }

    public int compareTo(Object other) {
        //Blah
    }
}

...and clearly there's an issue with clashing names there! Of course, this could be re-written using a single comparator, or using a compareTo method with a custom comparator passed in, but it's worth taking note of.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
0

Java generate code for conversion types before compilation. Also java use type inference for get correct type. For example :

List <Integer> mylist = new ArrayList<Integer>();
i.add(someInt);

In old style you can manually conversuin type:

Integer valI = (Integer)mylist.get(index);

Today compiler to "know" type elements of mylist and add (Integer) by itself. In result you write only it:

Integer valI = mylist.get(index);
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25