public static <A> void sort(A[] e);
You will not be able to use the above method with an int[]. Whenever possible the compiler will try to be helpful, and automatically box/unbox primitives for you, so for example the following will work public <A> A max(A a1, A a2);
/* ... */
void foo() {
int x = max(1,2);
}
this comes at the cost of boxing ints inside Integer, though.So, if you ignore for a moment primitives types, whenever you have generics, everything boils down to a single method accepting Objects and returning Objects. What the JVM does is to do runtime profiling of what actually you are passing to the generic method, and generate optimized routines for the "best case". In theory this is the best of the two worlds, because (unlike, let's say, C++) you will have a single implementation of the method, avoiding code explosion, but if you use it in an hot spot you get the optimized code.
In a way, it is quite wasteful, because you throw away a lot of information at compile time, just to get it back (and maybe not all of it) at runtime through profiling, but in practice it works quite well.
A side effect of this is this makes the JVM a wonderful VM for running dynamic languages like Ruby and Python, because that information is _not_ there at compile time. In particular GraalVM/Truffle and exposes this functionality to dynamic language implementations, allowing very good performance (according to their website [1][2], Ruby and Python on Truffle are about 8x faster than the official implementation, and JS in line with V8)
[1] https://www.graalvm.org/ruby/ [2] https://www.graalvm.org/python/
I’d say the best situation would be keep the type information at compile time but let the VM decide if multiple implementations are needed or not at runtime.
However, what if you have a collection of generic functions divorced from the arguments? There's no way from the function alone to determine the type params. So you can't write code that reflects over a collection of generic functions and dispatches solely on the type params.
And, while I've been speaking of functions, this really generalizes to any generic type. If you have e.g. a collection of PetTrainer<?>, and you have a code path in which you have a pet of type Dog or Cat, how can you use only reflection to choose a trainer upon which you can call Train(pet)? You can't.
(I don't Java, so please give me a little slack wrt syntax.)
Implementing that by hand using reflection just sounds plain wrong.
Would love to hear of a concrete real world example where this was an issue
The last bit of the GP comment is an example of the sort of thing that isn't possible with generics in Java, because the PetTrainer-of-Dogs and PetTrainer-of-Cats are indistinguishable at runtime. If you want to solve the problem with dynamic dispatch on the type-erased type of the first argument only, you could *stop using generics*, write a separate class for each generic instantiation you would have had, send every pet to every trainer, and have each trainer check the runtime type of their argument and do nothing if it's the wrong type. This probably isn't what anyone really wants to write or an acceptably cheap thing to do at runtime.
Nobody actually deals with PetTrainers but people do deal with MessageSubscribers that work more or less exactly as described, and the type system does nothing to help. For a concrete example of the horrors of double dispatch, you could see the wonderful book Crafting Interpreters.
But then you would probably need to cover just how aggressive the JIT is in the JVM and how the costs may not be what you would think they are.
The negative consequence of being ad hoc is that there's not even a very strong implication beyond the name that these different functions all do the same thing, and sure enough they often don't. So now either your users must read your documentation very carefully, or sometimes they will have unhappy accidents. This is made worse in many modern languages with type inference where your users may be mistaken about which of the functions they're actually calling since they don't always know the type of anything anyway...
Ad hoc polymorphism is over-used because it is relatively cheap to implement, and it's cheap to add more of these overrides later.
So generics are completely a language semantic concept in case of Java, with no performance detriment/benefit. Of course more information can be used up for better optimizations as well, see Rust’s or C++’s generics/templates.
For example
void <T extends Foo> bar(T f);
will, under the covers, create a function that looks like void bar(Foo f);
If you create a class class Foo implements Supplier<Bar> {
Bar get() { return new Bar(); }
}
The method signature for `Foo` does in fact return a `Bar` type and not some `Object` type even though `Supplier<Bar>` would imply that is erased. The same applies to if that generic was used within the method parameters.That generic type information is, in fact, stored off at the class level and can be extracted through Java's reflection API.
This is how magic like
json.parse("[1,2,3]", new TypeReference<List<Integer>>{});
is getting it's stuff done. It's creating a new anonymous class of "TypeReference<List<Integer>>" which the json library can then use to introspect and pull the generic information out and know that it should create a `List` of `Integer` rather than of `Long` or `Double` or a `Set`.This makes generics more than just a syntactic construction in Java.
An easy way to verify: Are generics in Clojure, Scala, or JRuby the same as Java (the programming language)?
class Foo implements Supplier<Bar> {
Bar get() { return new Bar(); }
}
Bar isn't a generic in Foo though (if we remove the implements-clause, that is very clear). It's only a generic in Supplier, so I don't see where the implied erasure quite comes from.For example, if we did something like
class Foo extends HashMap<Foo, Bar> {
@Override
Bar put(Foo f, Bar b) {
super.put(f, b);
}
}
The `Map` signature for `put` is `Object put(Object, Object)` due to erasures. However, because you are extending and specifying the generics, the overriden method ends up reifying the type.All this is to say that generics end up being a little more than just syntactic sugar.
class Base<T> {
T f() { return null; }
}
class A<T2> extends Base<T2> {
@Override
T2 f() { return null; }
}
class B extends Base<Integer> {
@Override
Integer f() { return null; }
}
class C {
Integer f() { return null; }
}
Base has a parameter T which is erased in Base.A has a parameter T2 which is erased in A.
B because B is not a generic class and nothing is erased from B.
Base has the same shape as A; B has the same shape as C.
In particular if you override a method in a derived class, you're allowed to return an instance of a more specific class (in your example, Bar is an Object so it is fine). At runtime, your example is equivalent to something like
interface Supplier {
Object get();
}
class Foo extends Supplier {
Bar get() { return new Bar(); }
}https://docs.oracle.com/en/java/javase/17/docs/api/java.base...()
Edit: sibling comment by cogman makes the case more thoroughly.
Edit: also HN mangles the link to Class.getTypeParameters()
For what it's worth, this seems to be a common misunderstanding where generics are concerned.
Also, I don’t see erased generics all that big of a deal — if there was no reflection (which is not that common feature in languages) one could not even differentiate between the two models. Haskell also does complete type erasure for example.
As for another view point, it is often brought up on HN that what made the JVM language ecosystem so thriving is exactly the type erasure model. C# effectively forces their idea of generics onto the whole platform, while JVM languages are free to choose their own model. I don’t know how true is that, but empirically it does seem to sound true (F# does share its generics model with C#, and the CLR has a history of getting some attempts at being a target which is later dropped. Though I assume it is more often due to it simply being a smaller target)
You can, even without reflection, because the Java generic type system doesn't have the parametricity property; you can detect runtime types with cast/instanceof. Haskell doesn't have non-parametric operations, so erasure is not observable.
Your method signature may look like
void foo(Iterable<Bar> b)
which would make you think of vtables and casting performance losses.However, Java's JIT is fairly cleaver. It can tell that you always call `foo` with an `ArrayList` and it can tell that `ArrayList`'s iterator always emits a `Bar` Object. From there it can elate a lot of the type tables and virtual dispatch to just be direct dispatch. It does that at the cost of a couple of added runtime checks to make sure those assumption's aren't violated.
The impact of generics on performance has, for me, generally been pretty low. I've seen a much higher impact due to java's memory model (which is getting fixed with Valhalla).
This, btw, is how JavaScript's and indeed most high speed JITs function.
Whether you call that an afterthought? I'm sure the designers had this in mind, but at the same time they painted themselves into a corner somewhat with earlier decisions and a huge dedication to backward compatibility. Their work on threads on the other hand shows some real forethought and they were able to avoid most of the pitfalls that a few other language impl's fell into.
Just to be pedantic int[] and long[] are both objects, but will be sorted using the first two signatures because the JVM uses different instructions for loading and storing elements from an array. Technically you could make a single function to return an array's length since it uses the same instruction.
Arrays are usually still preferred over collections in the case of primitive types (int[] etc.).
In the unlikely event that I'm modeling something that can be represented as a list of integers AND it's a significant performance bottleneck then, sure, I'll consider the array methods. But I don't recall the need arising in the last year or two.
Enterprise Java stuff just isn't often bottlenecked on that sort of thing. Network latency fills far more of my dreams ;)
The overhead of List<Integer> really can not be overstated, it can approach order 1000% memory consumption, speed is prima facie about half for dealing with collections, but in practice it can be much lower from the GC churn. Even for lists as small as a million entries this can be quite untenable.
You are not seeing different sides of the language but participating in different domains, application/business logic programming vs more system level stuff.
> Using Java:
Perhaps they meant it another way, but this makes it sound like there is runtime dispatch between these different signatures - there isn't. int, long etc. are unboxed types in Java, which are not Objects, and cannot be used for Object-based generic type-erasure. So the decision which of these sorts is going to be used is made by the compiler. All Objects are sorted using the third signature.