Re:Background: how we got the generics we have (2020)
by mrkeen on Thursday April 01, 2021 @07:52AM
(#26659284)
Does C# handle generics better than Java?
[ Parent
| on HN ]
Re:Background: how we got the generics we have (2020)
by paavohtl on Thursday April 01, 2021 @08:15AM
(#26659487)
C# implements proper reified generics. Generic types parameterised with different types are actual types in C#, while in Java generics is basically just syntax sugar for avoiding type casts. Each element in a List<byte> in C# takes 8 bits, while in Java each element in a ArrayList<Byte> is actually just an Object and therefore is a pointer (64 bits) to a separate allocation.
Re:Background: how we got the generics we have (2020)
by kaba0 on Thursday April 01, 2021 @11:41AM
(#26661894)
But at the same time, reified types will create a separate object for each template type, making some optimizations happen only for a type that was used often. While in Java, ArrayList for example will benefit regardless of the concrete type.
Re:Background: how we got the generics we have (2020)
by Felk on Thursday April 01, 2021 @08:13AM
(#26659471)
As "better" isn't clearly defined, here are some things that some people might consider superior:
- primitives or any custom value types/structs can be used. No need for boxing or method duplication for primitives. - type information available at runtime, no need to pass 'Class<T>' parameters. - type constraint 'new' available, which means it must have a default constructor so you can do 'new T()'. No need to use reflection or pass a constructor parameter. - type constraint 'notnull' available - class-scoped compiler enforced covariance and contravariance, though I think you can get similar results with java's "? extends T" and "? super T" constraints
Re:Background: how we got the generics we have (2020)
by accountLost on Thursday April 01, 2021 @08:04AM
(#26659401)
You can't easily create a instance of the generic type in java. for example :
return new T();
is possible in C#, not in java.
Re:Background: how we got the generics we have (2020)
by ohgodplsno on Thursday April 01, 2021 @08:28AM
(#26659580)
There is a way-ish, which is passing a Class<T> as an additional parameter and doing clazz.newInstance().
Definitely not pleasant though.