Beta
×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Hejlsberg Talk About Generics in C# and Java

timothy posted more than 9 years ago | from the from-the-source dept.

Java 128

An anonymous reader writes "artima.com has a very interesting interview with Anders Hejlsberg - the Borland guy now at Microsoft who can best be defined as MR C# - doing all the stuff that Borland wouldn't let him do. He discusses generics in C#, Java (1.5) and C++. Naturally there is the chance of bias but he does raise some interesting points againt Java's generics. Specifically that Java's genericised collections will have to box all primitive types as full objects, whereas C# does not. This is a big performance plus for C#. Java created the primitive types in the first place to address performance concerns but appears to be stepping sideways here. I can't help wondering if Sun has taken this approach to get the syntatic sugar in the language without requiring a bytecode change, but perhaps in a future VM version will allow primitive generics (obvioulsy forcing a bytecode regeneration)?"

cancel ×

128 comments

Sorry! There are no comments related to the filter you selected.

Performance of generics (1)

Frequanaut (135988) | more than 9 years ago | (#8113828)

" Specifically that Java's genericised collections will have to box all primitive types as full objects, whereas C# does not. This is a big performance plus for C#."

Do you have any references to back that up, or is this just "conventional wisdom"?

I'm not saying it's incorrect, but I'd wait until there are two implementations to compare.

Re:Performance of generics (5, Insightful)

hibiki_r (649814) | more than 9 years ago | (#8114078)

Just read a little further into the article. It seems that to avoid having to make changes in the VM, the Java generics have to become just like the current containers at the bytecode level. The main difference would be taht instead of having to type all the ugly type casts yourself, the compiler would do it for you. Obviously, this doesn't lead to any performance increases over Java 1.4 containters.

Compare this to, let's say, C++ templates, where the compiler makes a new copy of the template class specifically for each and every type you use on it. That makes the executable size increase a bunch, but it allows the compiler to pay the performance price, making the code perform almost like a program where a human programmer would have written a copy of the template class for each and every type you ever used it with.

Since the design of the java 1.5 generics is public knowledge, it's pretty easy for anyone with a reasonable programming knowledge to analyze it. It just seems that run-time efficiency wasn't the first thing in the designers minds.

Re:Performance of generics (2, Funny)

Frequanaut (135988) | more than 9 years ago | (#8114151)

"Just read a little further into the article. "

pfft. right. Like I'm going to read an article before commenting on it.

Re:Performance of generics (1)

the quick brown fox (681969) | more than 9 years ago | (#8114638)

For as long as I have been a Java programmer (4 years) at least, there have been collection libraries [sourceforge.net] for Java that are specialized for primitive types. One of their main reasons for existence is to avoid the performance overhead of boxing.

You can get a very rough idea of the performance gain here [onjava.com] (scroll down to "Trove Primitive Collections"). It's a significant difference.

Of course, for most apps that people are writing for Java (i.e. webapps for business), an optimization of this magnitude won't be noticable--all the time is spent in the DB or network. On the other hand, IIUC, MS intends to write large sections of Longhorn in C#.

Longhorn in C# (1)

gumpish (682245) | more than 9 years ago | (#8116603)

On the other hand, IIUC, MS intends to write large sections of Longhorn in C#.

Maybe that's why it's not due until 2006: they have to wait for commodity hardware to get fast enough to run it responsively.

Boxing in Java (2, Interesting)

Ianoo (711633) | more than 9 years ago | (#8113833)

Primitive types are boxed in C#, just automatically wrapped and unwrapped as required. But what he seems to fail to realise is that Java 1.5 is introducing this too, so that I will be able to define method(Object obj) and type method(12) and will receive a boxed Integer type. This should work fairly for generics too (I hope).

Re:Boxing in Java (2, Interesting)

drkich (305460) | more than 9 years ago | (#8113954)

Yes, C# does auto-boxing for the user. However, his point was that the Generics will not auto-box the primitive inside of an object.

So for instance if you have a List, you can not place an Integer with out unboxing it. Vice-versa, if you have a List you can not place an int into with out boxing it.

However if you have a List you can place an int into it directly without boxing it.

Re:Boxing in Java (1)

drkich (305460) | more than 9 years ago | (#8113993)

For some reason my > and < were removed, and I did not realize it.

So for instance if you have a List<int>, you can not place an Integer with out unboxing it. Vice-versa, if you have a List<Integer> you can not place an int into with out boxing it.

However if you have a List<int> you can place an int into it directly without boxing it.

Re:Boxing in Java (3, Interesting)

jovlinger (55075) | more than 9 years ago | (#8114000)

Automatic boxing and unboxing will be identical to manual boxing from a performance standpoint.

I got the impression that C# could actually use generics to instantiate the array at type int, rather than type Integer with autoboxing.

Re:Boxing in Java (1)

Steveftoth (78419) | more than 9 years ago | (#8114659)

That's what will happen in C# generics (supposedly).

It will be neat, but it adds more complexity to the system.

Re:Boxing in Java (1)

jovlinger (55075) | more than 9 years ago | (#8115023)

It will be neat, but it adds more complexity to the system

Yes, but complexity at the right place: in the compiler. Exposing the boxing/unboxing distinction to the programmer makes it easier to generate good code, but you now have all this manual wrapperized stuff to deal with all over your code.

On the other hand, research has shown that even naive analysis will allow you to generate quite good code from LISP, which is nominally completely statically type-opaque (you have no idea WHAT you have until you ask).

So generating good code from a system which makes int a subtype of object is actually not that impossible; solve the problem once, in the compiler, instead of making the programmer solve it, over and over again.

Re:Boxing in Java (1)

Steveftoth (78419) | more than 9 years ago | (#8115471)

Um. It also adds complexity to the runtime, and to the programmer.

Generics is not like a recompile and go situation. You have to rewrite all your code that uses lists and collections if you want to use the new generic features, otherwise you get new compile errors when useing the collections. This is not as bad for C# as compared to Java since C# is a much younger language and thus the API is also smaller (so far).

Since in .NET CLR a List is actually compiled into a list that only holds ints (and not objects), it actually has a completly different codepath then a List or List. Thus you have potentially hundreds of versions of the List code in memory. All to handle slightly different versions of the same code. So while you are getting gains from not having to box your Integers, you are losing gains from having a larger code footprint.

It's not a win-win situation with generics. Just by defining a HashMap in your code you get a whole new class that must be created and loaded into memory.

Generics is also a pita because it doesn't actually solve all your problems. It's nice for simple lists, but for hash maps it' just doesn't work. Most real life Maps that I've encountered can have a wide variety of objects in them, so you end up doing if instanceof .. then.. else if instanceof... on the value retreived from a Map. Not the best solution, but then again the best solution would be custom code for every map, with bounds checking on the inputs (which generic programming does NOT do, if it did some form of bounds checking then I might be impressed).

I personally don't think that generic programming is much good for data structures more complex then lists. If you have to generate a new class for every type of Map that the programmer might want to use then you will have many classes that do not need to be loaded.

Re:Boxing in Java (1)

chicogeek (688521) | more than 9 years ago | (#8118744)

I think you're mistaken regarding the need for recompiling your C# source code before moving to Whidbey. First of all, generics are optional and there will still be a List class that is perfectly happy to take your Object-derived instances and hold them for you.
Since in .NET CLR a List is actually compiled into a list that only holds ints (and not objects), it actually has a completly different codepath then a List or List.

WTF are you talking about? The only way you're going to get an instance of a class that implements IList and only holds ints is to do this ArrayList intList = new ArrayList(); If you just choose ArrayList myList = new ArrayList(); you get a non-specialized version of the IList-supporting class. Me thinks you don't know what you're talking about.
Thus you have potentially hundreds of versions of the List code in memory.

If you have hundreds of specializations of the generic container, then yes, you will have have hundreds of new types inserted into the AppDomain. However, if you just instantiate a new non-specialized collection class, you don't get a new class definition.

Okay, please tell me what type of application development you do? Most associative arrays that I use map an ID to and instance. Say person ID to the container that holds that person. Please tell me how you're mapping a useful key to disparate object types, I'm just curious.
This is the topper:
Generics is also a pita because it doesn't actually solve all your problems.
No one said they're the silver bullet, but as someone else indicated, spend some time deriving classes from CollectionBase and you'll quickly appreciate having strongly typed collections with no heavy lifting on your part.

Re:Boxing in Java (1)

chicogeek (688521) | more than 9 years ago | (#8118768)

Of course this:
ArrayList intList = new ArrayList();

Should have been this:
ArrayList<int> intList = new ArrayList<int>();

Re:Boxing in Java (2, Informative)

Steveftoth (78419) | more than 9 years ago | (#8118880)

My bad, I should to have said that a Generic List is compiled at runtime into a seperate class by the JIT.

Since in .NET CLR a List is actually compiled into a list that only holds ints (and not objects), it actually has a completly different codepath then a List or List.

WTF are you talking about? The only way you're going to get an instance of a class that implements IList and only holds ints is to do this ArrayList intList = new ArrayList(); If you just choose ArrayList myList = new ArrayList(); you get a non-specialized version of the IList-supporting class. Me thinks you don't know what you're talking about.

Here's what I'm talking about from the second page of the article, Hejlsberg says that there will be lots of class definitions floating around in memory.

Bill Venners: How do generics work in C#?

Anders Hejlsberg: In C# without generics, you are basically able to say class List {...}. In C# with generics, you can say class List {...}, where T is the type parameter. Within List you can use T as if it were a type. When it actually comes time to create a List object, you say List or List. You construct new types from that List, and it is truly as if your type arguments get substituted for the type parameter. All of the Ts become ints or Customers, you don't have to downcast, and there is strong type checking everywhere.

In the CLR [Common Language Runtime], when you compile List, or any other generic type, it compiles down to IL [Intermediate Language] and metadata just like any normal type. The IL and metadata contains additional information that knows there's a type parameter, of course, but in principle, a generic type compiles just the way that any other type would compile. At runtime, when your application makes its first reference to List, the system looks to see if anyone already asked for List. If not, it feeds into the JIT the IL and metadata for List and the type argument int. The JITer, in the process of JITing the IL, also substitutes the type parameter.

Bruce Eckel: So it's instantiating at runtime.

Anders Hejlsberg: It's instantiating at runtime, exactly. It's producing native code specifically for that type at the point it is needed. And literally when you say List, you will get a List of int. If the code in the generic type uses an array of T, that becomes an array of int.

Class proliferation (2, Insightful)

Latent Heat (558884) | more than 10 years ago | (#8119059)

I think what is going on is that you will get a list class for each separate value type and then one list class that will hold all the reference types (the value type is sort of like pointer).

I mean, how many value types are there already? So you get a couple instantiatians of the class instead of one. And if you are really worried about footprint, you can use only reference types in your list.

Re:Class proliferation (1)

Steveftoth (78419) | more than 10 years ago | (#8119083)

Thanks to Structs, there are an unlimited number of them. I dunno, maybe it's better, maybe worse. I don't know for sure.

Re:Boxing in Java (1)

Steveftoth (78419) | more than 10 years ago | (#8118960)

No one said they're the silver bullet, but as someone else indicated, spend some time deriving classes from CollectionBase and you'll quickly appreciate having strongly typed collections with no heavy lifting on your part.

I never pass around collections outside of my own programming interfaces. Otherwise you have other problems.

Most of them relate to bounds checking and not type checking. Bounds checking which may change at runtime, rather then simple type checking which is rather static. I personally don't like the way that C# is implementing generics at runtime because it's like the C++ way which is to create seperate code for any possible variation, when in fact the code is the same. Doesn't really matter much to me because I don't use C# yet though.

Re:Boxing in Java (0)

Anonymous Coward | more than 9 years ago | (#8118540)

Well, why not just use Lisp instead of C# or Java? There are mature, high-performance common lisp native-compilers AND bytecode VMs. Why sign up to hypeware from M$ and $un?

Nothing's changed here... (1, Offtopic)

Dr. Bent (533421) | more than 9 years ago | (#8113859)

Specifically that Java's genericised collections will have to box all primitive types as full objects, whereas C# does not. This is a big performance plus for C#.

The Java collections operate this way right now (in JDK 1.4) and AFAIK have operated this way since the beginning. You can't add a primitive type to a collection, genericised or not, it has to be a first class Object. In terms of performance, whether or not the conversion is done explicitly or automatically shouldn't matter. If anything, the automatic conversion with autoboxing should be faster because it can be optimized "under the covers" in the compiler or the JVM.

I don't see how this performance issue is related to generics in C# vs Java.

Re:Nothing's changed here... (2, Insightful)

bay43270 (267213) | more than 9 years ago | (#8114210)

This is just my interpretation. I'm not a C# developer:

Its faster because C# ints don't have to be converted. They are already objects (more like second class structure-like objects). When you define a collection of ints in C#, there is no boxing needed to populate the collection.

You are right about Java, however. The byte code looks the same if you use generics, or not. There won't be any performance loss from old code, just better looking code.

What the article is saying, is that adding primitives to a collection is slower than adding objects (due to boxing - automatic or otherwise). This is supposed to negate the benefits of using primitives (rather than objects) in Java.

Re:Nothing's changed here... (1)

Dr. Bent (533421) | more than 9 years ago | (#8114763)

What the article is saying, is that adding primitives to a collection is slower than adding objects (due to boxing - automatic or otherwise).

Yes, but the title of this article is "Generics in C#, Java, and C++". My question is, what the hell does autoboxing in Java have to do with generics? With generics, only objects can be put into collections. Without generics, only objects can be put into collections. Nothing's changed!

Of course, I think the real point of this article is to use the topic of Generics as an excuse to empahsise the fact that Java collections can't hold primitive types. Considering the other objective advice [nwsource.com] that's come out of Mircosoft, I can't say I'm suprised.

Re:Nothing's changed here... (4, Informative)

sab39 (10510) | more than 9 years ago | (#8115118)

It doesn't have anything to do with autoboxing in Java, but it has everything to do with boxing in Java versus C#.

Both C# and Java require boxing if you want to put an int into an object variable. They differ in whether that boxing is automatic or not (at least until Java makes it automatic in 1.5), but that's irrelevant: it still happens, so the performance impact is the same in both languages.

However, if you're trying to put that same int into an ArrayList<int>, the two languages are very different.

In Java, ArrayList<int> is really just ArrayList<Object> under the covers, and stores its contents into an array of type Object[], so the boxing operation still needs to happen. Hence, there's a performance hit.

In C#, ArrayList<int> is interpreted as such at the runtime level and the JIT compiler creates native code for it that stores the contents in an array of type int[]. When you store values into that array, no boxing is needed, automatic or otherwise. No performance hit.

Both C# 1.1 and Java 1.4 collections can hold primitive types if you box them. In Java 1.5, you get some extra syntactic sugar (which C# had from day one) but the boxing still happens. In C# 2.0, generic collections can hold primitive types without boxing. That's the difference that he's trying to get across in this article, and why it's specific to generics.

All of this is explained very clearly in the article and it amazes me that so many people can't grasp it...

Re:Nothing's changed here... (1)

rowanxmas (569908) | more than 9 years ago | (#8115723)

I don't think that it makes List into int[]... since it sounds like you can put whatever into List, which means that you could have a subclass of int.

The impression I got was that autoboxing was not necessary because everything is always boxed ( i.e they have no primitves in C# ).

Please correct me if I'm wrong.

Re:Nothing's changed here... (3, Informative)

sab39 (10510) | more than 9 years ago | (#8116482)

I'm afraid you are wrong.

While "int" is treated "as if" it were an Object in the CLR, and behaves as if it was a subclass of Object, it really is a value type: It's allocated on the stack, cannot be subclassed, and is passed by value when it's used as a method parameter or return value.

The same goes for all the other built in primitive types (float, decimal, double, long, short, bool, char etc), along with user-defined Structs and Enums. These are all considered "Value Types" in the CLR.

When instances of value types need to be treated as Objects, they are boxed, just like in Java, except that it's transparent and automatic and there's no separate class that represents the boxed type - the distinction Java makes between int and Integer simply doesn't exist in C#. (System.Int32 is just an alias for int and isn't equivalent to Integer at all in any way).

The article clearly states that in Generic C#, the JIT actually creates specialized binary code whenever a generic class is instantiated with a value type argument. It even uses the example of List<int> turning into int[] (remember value types like int can't be subclassed, so the subclass problem doesn't arise).

C# provides the "illusion" of no primitives, but it's certainly not true that everything's always boxed. It just provides a more elegant and flexible model of boxing than Java does.

Re:Nothing's changed here... (2, Insightful)

the quick brown fox (681969) | more than 9 years ago | (#8114686)

In C#, no conversion/wrapping/boxing, whether manual or automatic, will be necessary. The parameterized type will actually store the values in their unvarnished, primitive form.

C# generics are smart enough to treat value types differently than reference types (or what you're calling a "first class Object"), while Java generics are not.

Why Generics? (2, Interesting)

HaiLHaiL (250648) | more than 9 years ago | (#8113941)

I'm a Java developer of 4 years and I'm unimpressed by generics. Why have all those 's dirtying up my code, only to enforce strong typing on my collections? If strong typing is really important, I can create my own strongly-typed collection. Otherwise, there's something called GOOD CODING, along with runtime exceptions, which enforce it. I don't see the need for all that extra ugly syntax just to enforce it at compile time.

Re:Why Generics? (1)

HaiLHaiL (250648) | more than 9 years ago | (#8113980)

"all those <>'s"

(who would have thought I need to use html entities in posting "Plain Old Text"?)

Re:Why Generics? (1)

sfjoe (470510) | more than 9 years ago | (#8114011)



I think it's a marketing thing. Every now and again, the PHBs have a need to scream, "Look - we added new stuff"!!!
It doesn't really matter if the new stuff is useful or necessary, just so long as they can slap a "Now With 14% More Creamy Goodness" sticker on the side of the box.

Re:Why Generics? (2, Insightful)

the eric conspiracy (20178) | more than 9 years ago | (#8114147)

Why have all those 's dirtying up my code, only to enforce strong typing on my collections?

Because compile time errors suck much less than run time errors.

Re:Why Generics? (4, Insightful)

Aniquel (151133) | more than 9 years ago | (#8114150)

A couple different reasons, actually. First, as mentioned in the article, performance. If you're using generics (come on, call them templates!) and compile-time checking, then you don't need to do the dynamic casting at run-time (c# doesn't, according to the article).

Second, don't scoff at compile-time type checking - I've run into problems on large java projects where there's been some confusion as to what, actually, has been stored in certain collections. Generics prevent this.

It comes down to this: How much help do you, as a programmer, want?

Re:Why Generics? (1)

Steveftoth (78419) | more than 9 years ago | (#8114689)


Second, don't scoff at compile-time type checking - I've run into problems on large java projects where there's been some confusion as to what, actually, has been stored in certain collections. Generics prevent this.

I've run into this too, and you know what the solution is? To go to the programmer's cube who is responsible for the code and beat him/her with your clue stick until they wise up.

Re:Why Generics? (1)

Mr. Shiny And New (525071) | more than 9 years ago | (#8114874)

Clue sticks can't solve all humanity's problems; we're too far gone as a species for that. But if you can have an automated tool enforce the rules, why not use it? Admit it: Generics make it easier to understand the code, because you are always sure of what you get. Nobody is FORCING you to use generics. But if you do use them, your code will be more readable, even if you are a lousy programmer.

Re:Why Generics? (1)

aled (228417) | more than 9 years ago | (#8117173)

"Clue sticks can't solve all humanity's problems"

Who says they can? It just will make you feel better and release some stress beating the hell out of someone. Much better if he's responsible of something.

Re:Why Generics? (1)

Steveftoth (78419) | more than 9 years ago | (#8117215)

But generics don't solve the problem of bad programmers, it just forces them to be more creative.

And no, I don't think that generics make it any easier to read the code

If someone hands you this interface.
public interface CrappyInterface {
public Map<String,String> getStringMap();
}

and tells you that their class implements it, what good has generics done you. Nothing. It buys you compile time saftey, sure, but what does the interface actually do? That requires documentation, and in the documentation you have to specify what strings the map uses and what they mean. There has yet to be a programming language invented that is truely self-documenting. Until that comes, we will still need good documentation and clue sticks to hit the people who don't document their code correctly.

Re:Why Generics? (1)

Hast (24833) | more than 10 years ago | (#8121877)

That's not the problem he's talking about. The main point with generics is that if you have something like

List names;

then you don't know anything about what type to get out of that list. And if the coder had done something strange like put numerical references to a database with names in the list then you'll get a run-time error. If the list instead is

List names;

then you at least know something about what to expect from the List. (And you know that you have to hunt down documentation for it since it's not obvious what it does.)

Re:Why Generics? (1)

Hast (24833) | more than 10 years ago | (#8121882)

"You shall use preview, you shall use preview, you..."

The first example should read (as it does) List names;

The second example should read List<Integer> names;

Re:Why Generics? (1)

heinousjay (683506) | more than 9 years ago | (#8115373)

And what happens when you're on a team of 100, and you don't know everyone's contributions?

Your attitude just doesn't scale.

Re:Why Generics? (1)

Steveftoth (78419) | more than 9 years ago | (#8117108)

Neither do software teams of a hundred people!

Neither Java or C# can solve the problem of having too many people on the same project with bad management.

Re:Why Generics? (4, Insightful)

Naerbnic (123002) | more than 9 years ago | (#8114305)

"To ask the question is to know the answer"

The easiest response to that, is the point you just brought up. To get some semblance of compile time type checking, you'd have to make your own type. There are various disadvantages to this, among which are:

  • It uses up your precious time to do what should be almost automateable
  • You can't easily fit back your custom class into the standard classes Java would provide. Your derived class, for instance, would be returning class Foo instead of object. Java doesn't allow you to override methods that vary only by return type
  • Depending on naming, the new class may not be apparent to someone using your API to what it is, especially if your custom class is simply a wrapper around a standard class


As for the benefits of generics, a basic one is that it makes the intent of the code clearer (since you don't want to make a custom type, for the reasons above). The other major one I can come up with right now, is making your interfaces clearer to people who would use your classes. By fully specifying the type (including what is supposed to be in collections), you can make sure the class user is clear on what the interface to a method is, and if he makes a mistake, the compiler will tell him. This means you don't have to deal with all the messy exception handling and such that would go along with just using Object base types.

I am agreed that the < > syntax can be too verbose at times, especially with something like LongClassName<AnotherName> foo = LongClassName<AnotherName>(). Of course, this leaves us with a quandary, since on the one had we want to be able to easily see and specify types of everything, which would suggest using full typenames everywhere. On the other hand, we could introduce typedef like functionality, but that would have some problems of clarity. It seems that Java has historically, and still is taking the first approach.

Re:Why Generics? (1)

hibiki_r (649814) | more than 9 years ago | (#8114308)

From your post, it seems that you're probably not working on a large (200K+ lines) application, where more than 3 or 4 programmers are involved in development.

If I could be the sole maintainer of all of the code in my project, I'd not see all that big of an advantage in generics. the main thing would probably be avoiding all of those ugly typecasts all java programmers have to live with, but all in all It'd not be a big deal. However, on a big project, I REALLY, REALLY want to be able to easily know which class the members of a collection are, and I don't want to have to rely on naming conventions or the comments of any of my fellow programmers to do so. Is everyone going to write top notch code every single day for 2 or 3 years? I don't think so. On any major team effort, anything that can save the programmers time counts, and should be investigated. This includes generics, no matter how good or bad the implementation is.

It's a pity though that the way the java 1.5 generics are going to be implemented is not all that satisfactory to me. I find miself agreeing with the article's author, even though I'd rather be shot in the head than having to develop on a MS-centric environment. Is there really no way to keep compatibility with 1.4 classfiles while implementing generics in the C# style?

Re:Why Generics? (1)

rlowe69 (74867) | more than 9 years ago | (#8114331)

I'm a Java developer of 4 years and I'm unimpressed by generics ... I don't see the need for all that extra ugly syntax just to enforce it at compile time.

It's a good thing then that you don't have to use generics if you don't want to. The choice is great, isn't it?

Personally I do a lot of development with the Java collection framework. Generics will save me a lot of time and code spent checking Object types.

Missing the point (1)

devphil (51341) | more than 9 years ago | (#8114694)

If strong typing is really important, I can create my own strongly-typed collection.

Over and over and over again...

something called GOOD CODING, along with runtime exceptions, which enforce it. I don't see the need for all that extra ugly syntax just to enforce it at compile time.

Bwahaha. Nice troll. Ask any serious programmer, and he/she will tell you that good coding practice calls for as many checks as possible during compilation, while it's still in the lab. "Whew, it got caught during runtime!" is a shitty excuse when the run time in question was the demo in front of the customer, or during actual use on the flight deck, etc.

Re:Missing the point (1)

Eponymous, Showered (73818) | more than 9 years ago | (#8115221)

Ask any programmer who has worked on large system using strongly-typed and untyped languages which they prefer. They're probably all still working in Scheme/Lisp or Smalltalk and never went back to their tinkertoys, aka C++.

Re:Why Generics? (1)

Pentagram (40862) | more than 9 years ago | (#8114812)

Why have all those [< >]'s dirtying up my code, only to enforce strong typing on my collections?

I was assuming that the < >s would remove the need for the much dirtier

fooCollection.add(new Double(fooPrimitive));

and

fooPrimitive = ((Double)(fooCollection.get(xxx))).doubleValue();

etc.

Or is this still required?

Re:Why Generics? (1)

rowanxmas (569908) | more than 9 years ago | (#8115844)

I think so, I believe that you can now say:
List<double> dList = new List<double>;
dList.add( 42 );
double value = dlist.get(0);

Re:Why Generics? (2, Insightful)

Dr. Bent (533421) | more than 9 years ago | (#8114929)

If strong typing is really important, I can create my own strongly-typed collection.

Sure you can. You can also write the Java bytecode by hand, in hexadecimal, using only your pinky fingers to type.

The point of generics is to reduce (significantly) the amount of time it takes to create strongly typed collections. In addition, it makes those collections more reusable. For example, if I make a strongly typed Iterator, either I have to make an Iterator that doesn't inherit from the java.util.Iterator interface (meaning that it won't be compatable with classes that already use that interface), or I have to create a subclass that has two sets of methods (one strongly and one weakly typed) for every operation. Neither of those options are ideal. Generics provide a 3rd option that is much more elegant and safe.

Re:Why Generics? (0)

Anonymous Coward | more than 9 years ago | (#8115074)

Why have all those <>'s dirtying up my code?

By gosh, you're right! Why:


MyType aMyType = new MyType();
HashMap aHash = new HashMap();
aHash.put(key, aMyType);
try
{
((MyType)aHash.get(key)).doSomething();
}
catch( ClassCastException e)
{
System.out.println("Whee!!! Runtime errors are so much more fun than compile-time errors");
}


is so much cleaner than:


MyType aMyType = new MyType();
HashMap<MyType> aHash = new HashMap();
aHash.put(key, aMyType);
aHash.get(key).doSomething();


If you'd bothered to read the article, you would've noticed that Java's implementation of Generics is completely in the compiler. Therefore, if the situation doesn't call for them, nothing changes from the way it currently works. But adding a couple of <>'s to your code is a hell of a lot easier and more maintainable than writing up your own type-safe collection.

Re:Why Generics? (1)

tyrecius (232700) | more than 9 years ago | (#8117249)

Let me get this straight. On the one hand I can declare the contained type once at declaration time. On the other hand, I can declare the contained type every time it is used.

Speaking from personal experience, objects are used at least several times after being declared.

Seems reasonable... (1)

kieranbenton (642814) | more than 9 years ago | (#8114083)

I've been waiting for a long time before generics get released for C#. At least now e know they're doing them properly. Sounds like they will outperform java significantly... at least with value types.

You (and you are not alone) are an idiot (0)

Anonymous Coward | more than 9 years ago | (#8116996)

I don't mean to pick on you indivually here, but anyway..

Sounds like they will outperform java significantly... at least with value types.

I know it's too much to ask for on slashdot... But I guess if you had actually read the fucking article (which was interesting) you would know that you are an idiot.

The article clearly states that there is a performance benifit for both value types (which don't have to be boxed) and reference types (which don't have to be downcasted).

There.

It does seem any "performance" argument is bogus (1, Interesting)

spitzak (4019) | more than 9 years ago | (#8114173)

Not having to "box primitives" is certainly an advantage in that it makes the language cleaner. So I think C# is better because of this. But I find it hard to believe that this "improves performance". I would think the whole reason for treating primitives differently is to improve performance, as they can go through optimized code rather than the path taken by normal user-defined objects. So a collection of boxed primitives in Java may be slower than non-boxed primitives in C#, but this was done so that a collection of normal objects is faster.

Though really, I want to know why these languages have to be written so "primitives" are special at all. I would really like to be able to subclass an int or other built-in, and having "methods" on an int would be nice (even if you can't define new ones). The main reason is so you don't have to rewrite if you change your mind about whether type A is a primitive or something you define. Can't the byte compiler do a bit of work so any fast-path for the primitive can be used, without building in such restrictions to the syntax?

Re:It does seem any "performance" argument is bogu (1)

ivan256 (17499) | more than 9 years ago | (#8114523)

The types of performance problems you're talking about are orders of magnitude away from the performance problems that users percieve when using Java applications though. The same problem exists in C#, and users will percieve it as slow too as soon as average and below average programmers start using C# for applications that people actually use.

When somebody says that a java application is painfully slow, the problem usually stems from the use of stock objects and the programmer's lack of understanding of the internals of these objects. There's a rich library of complex and convienient objects available for Java that allow Java programmers to quickly implement features that take much longer to implement in other languages, and programmers use them freely. Unfortunatly many of the operations on these objects have a high order of complexity that is hidden by operators like a simple '+'. This fools the unknowing application writer into thinking this is a fast operation, even if it's not. When Java applications are written by skilled programmers who take the cost of object operations into account when they write their software, they are actually quite snappy, and on modern machines the performance gained through different primitive implementations is only visible in benchmarks and scientific applications.

Re:It does seem any "performance" argument is bogu (2, Interesting)

dustman (34626) | more than 9 years ago | (#8114782)

The types of performance problems you're talking about are orders of magnitude away from the performance problems that users percieve when using Java applications though.

I disagree here.

Think of Moore's law, processor speeds, etc... Java is a fast enough language for doing just about anything a user needs to do. Even if java were only 25% as fast as native code, that would be 2 cycles of Moore's law, 36 months, 3 years ago. (And, java is much faster than 25% of C, check here [bagley.org] )

3 years ago, users were all doing the same things they are doing today.

A couple of exceptions apply, of course: scientific computing, games, etc, tax the hardware pretty heavily.

But, the primary reason that Java is perceived as slow by users is the terrible speed of the GUI.

All the widgets are implemented in Java directly. This is almost like the same exception as game software, since all this rendering code involves moving around lots of memory, etc...

The GUI matters more than anything to user perception of slowness.

An old 14mhz 68000 amiga often "felt" faster than a 50mhz 386, because the amiga's os/gui were very responsive, while the 386 was running win3.1

Look at the recent developments with the linux kernel. Compare X responsiveness with a preemptible low-latency kernel, and how the whole machine "feels" better.

By going with preemption and low-latency, the overall throughput of the machine is actually slightly slower. But it feels loads better.

C# and the .NET framework use native code libraries for the GUI. It will never have the same perception of "slowness" that java has.

Re:It does seem any "performance" argument is bogu (1, Interesting)

Anonymous Coward | more than 9 years ago | (#8115241)

One other area where java gets a bad rap for being slow is in startup time. I write a lot of small java apps and continually loading the jvm adds about a second to the startup time on my machine. I've gotten around this by creating a RAM disk at startup and copying the jvm executable and jars over. This gets rid of the noticeable startup time. JVMs should come with the option of loading into memory at startup...it would help dispell the myth that java, by nature is too slow.

But you're right about the GUI...that's the single biggest fuck up that Sun made. IBM has done better as SWT comes pretty close to being fully responsive (though it still makes it possible to be unresponsive if you write bad code.)

Re:It does seem any "performance" argument is bogu (1)

ivan256 (17499) | more than 9 years ago | (#8115571)

I would agree with you if it were impossible to make a responsive GUI in Java. It isn't. Most unresponsive Java GUI's are slow due to poor choice of object operations when responding to events, not because it's using 'non-native' GUI calls, which at worst add a layer of library indirection.

The slowness we're talking about isn't typically miliseconds, it's whole seconds. You're talking about graphical slugishness, which is a whole differen't issue, and one that most users don't even notice.

Re:It does seem any "performance" argument is bogu (1)

chicogeek (688521) | more than 9 years ago | (#8114907)

So a collection of boxed primitives in Java may be slower than non-boxed primitives in C#, but this was done so that a collection of normal objects is faster.
Faster than what? Faster than the Java implementation would have been had they done it properly (i.e. modify the byte code, not rely on type erasure, etc). Or are you saying that this ommision makes the Java generics implementation faster than the C# generics implementation?

Re:It does seem any "performance" argument is bogu (1)

spitzak (4019) | more than 9 years ago | (#8115073)

What I'm saying is it *doesn't* make the C# implementation faster. If C# is written intelligently, the best it can do is make it the *same* speed.

Now C# could in general be written better and do the *same* job faster. And I agree that this ability makes the language *better*. But saying this better feature of the languages is the *reason* it does something faster is bogus. I am pretty certain the artificial differentiation between primitives and objects in both languages is in order to make them more efficient, and removing that restriction by defninition will slow them down, or at least not make them faster.

Re:It does seem any "performance" argument is bogu (1)

spongman (182339) | more than 10 years ago | (#8122318)

There are two types of objects: 1) value types (primitives, enums, structs, etc...), and 2) reference types (objects and boxed value types).

There are two types of collections: 1) collections of value types, and 2) collections of reference types.

Collections of value types are usually faster because they don't require: 1) individual heap storage for each element, and 2) dereferencing references to elements.

Java doesn't have generic collections of value types.

C# will potentially on-demand JIT compile many different versions of a generic collection, one for all reference types, and one for each value type.

The performance of Java's generic collections will be similar to C#'s 'reference type' instantiation of a generic collection. But C#'s 'value-type' instantiations will usually be faster than both C#'s and Java's 'reference-type' versions, in some cases significantly faster.

Re:It does seem any "performance" argument is bogu (1)

the quick brown fox (681969) | more than 9 years ago | (#8115790)

It's not simply that primitives go through optimized code in collections. Primitives in Java are fundamentally different than objects in that they are stored inline with their context (either the stack, an array, or the object they're a member of), whereas objects are always referred to by reference and stored somewhere on the heap.

<oversimplification>So for example, an int[10] takes 40 contiguous bytes (4 bytes per int) on the heap. That block contains the actual values of the ints. An Integer[10] also takes 40 continguous bytes on the heap, but now those are just references (4 bytes per object ref, on x86 at least) to 10 4-byte blocks, potentially scattered around the heap.</oversimplification>

Imagine how much longer it takes to compare two Integer[]'s than two int[]'s. The former involves a following a reference to get each value, the latter is just pointer addition. Furthermore, primitives allow the JIT compiler to create far more optimized native code. (Your hypothetical "bit of work" would have to fall back any time a public method takes an int argument, and ripple from there on inward whenever that reference is passed.)

Not to say there isn't a class of problems/programmers for which subclassable "primitives" may be appropriate and valuable. If you truly find yourself in that situation, it might be time to consider Python or Ruby.

you, sir, are a retard (0)

Anonymous Coward | more than 9 years ago | (#8117062)

So a collection of boxed primitives in Java may be slower than non-boxed primitives in C#, but this was done so that a collection of normal objects is faster.

I'm assuming that you read the article, and are therefore just dumb. Let me spell it out. The article says (all in theory here) that C# generics are faster for both primatives and reference types.

Re:you, sir, are a retard (1)

spitzak (4019) | more than 9 years ago | (#8117277)

Yes, but this is apparently because it is *better written*, not "because it can do primitives" which the Slashdot writeup suggests. In theory it could be slightly faster if it *didn't* do primitives due to some slight simplification of the generics code (though if intelligently written it would just be the same speed as now).

Let me reiterate: adding primitives should not slow it down, but I can think of no concievable explanation for it making it faster, so the slashdot writeup is wrong.

The possibility that C# is written by smart people and Java is written by idiots may mean that the C# is faster. But that does not mean the reason it is faster is because of the treatement of primitives.

Now confirmed, you are an idiot. (0)

Anonymous Coward | more than 9 years ago | (#8117458)

I wrote: The article says (all in theory here) that C# generics are faster for both primatives and reference types.

You wrote: Yes, but this is apparently because it is *better written*, not "because it can do primitives"

Wrong. C# generics are (in theory) faster than Java's because

A) primatives don't have to be boxed because generics are supported by the run-time.

B) references don't have to be downcast at runtime.

Did you *read* the article???

I'll skip the rest of your moronic post.

I give up (1)

spitzak (4019) | more than 10 years ago | (#8119233)

You really can't say anything positive about Microsoft here. I go and say that C# may be "better written" and people jump like crazy to call me an idiot. Hey: there are real intelligent people working at Microsoft! I don't like what they do all the time, but they are not stupid.

Face it, Java does not do primitives in the containiers. It does not do them "slower", it just DOES NOT DO THEM!!!

Therefore C# is not "faster". It is instead, better designed.

And I would like it if somebody came up with a language that did not have these artificial restrictions in it. C# is closer but it still treats primitives different all over the place.

Re:you, sir, are a retard (1)

the quick brown fox (681969) | more than 9 years ago | (#8117883)

Yes, but this is apparently because it is *better written*, not "because it can do primitives" which the Slashdot writeup suggests. In theory it could be slightly faster if it *didn't* do primitives due to some slight simplification of the generics code (though if intelligently written it would just be the same speed as now).

This is not true at all. C# generics can be faster for primitives because the JITter compiles a separate native image when the type parameter is a primitive. It sounds like you think the generic collection classes in C# have some kind of conditional logic in it to deal with primitives vs. objects. In fact it's nothing like that... the JIT compiler separates the different cases out at JIT time, and creates distinct classes in memory as necessary. The classes that target primitives, unlike their Java counterparts, don't need primitive values to be boxed/wrapped... so they can be faster and use less memory.

The only (good) reason Java doesn't support this in their impl of generics is for backward compatibility with older JVM's.

Re:you, sir, are a retard (1)

spitzak (4019) | more than 10 years ago | (#8119189)

C# generics can be faster for primitives because the JITter compiles a separate native image when the type parameter is a primitive.

Of course. That's why I said that it does not have to be slower. But that has nothing to do with whether C# handles non-primitives in a container faster. It may make them slower, or if correctly written it makes them the same speed. But it does not make them faster!!!

The only (good) reason Java doesn't support this in their impl of generics is for backward compatibility with older JVM's.

Good point, though I thought they also introduced syntax problems so that this could not be fixed even if they were willing to break the JVMs.

were you dropped on your head a lot? (0)

Anonymous Coward | more than 10 years ago | (#8119551)

But that has nothing to do with whether C# handles non-primitives in a container faster. It may make them slower, or if correctly written it makes them the same speed. But it does not make them faster!!!

Wrong. A C# generic containter of reference objects (aka non-primatives) is in theory faster than a non-generic C# container or a generic Java container or a non-generic Java container - because there is no need to do a checked downcast when accessing an object in the container.

Can I spell that out any more clearly for you? Any big words that you didn't quite get?

Man, I think I'm being trolled here - are you really this dumb?

Re:were you dropped on your head a lot? (0)

Anonymous Coward | more than 10 years ago | (#8121214)

Jeeze, give the guy a break. I mean, he may be wrong, but you don't have to be a dick about it.

Re:you, sir, are a retard (1)

the quick brown fox (681969) | more than 10 years ago | (#8120808)

Sorry, I didn't realize you were talking about containers of non-primitives. I agree that the fact that C# jits distinct native code based on primitive types does not, in and of itself, make the non-primitive case any faster.

Though, AC poster at this level pointed out that the fact that the CLR does not erase the type information the way the JVM does could let you skip a cast. (Not likely to make much of a difference, IMO...)

Re:It does seem any "performance" argument is bogu (1)

spongman (182339) | more than 10 years ago | (#8122354)

RTFA

For example, with Java generics, you don't actually get any of the execution efficiency that I talked about, because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. So the compiled image for List<T> is like a List where you use the type Object everywhere. Of course, if you now try to make a List<int<, you get boxing of all the ints. So there's a bunch of overhead there. Furthermore, to keep the VM happy, the compiler actually has to insert all of the type casts you didn't write. If it's a List of Object and you're trying to treat those Objects as Customers, at some point the Objects must be cast to Customers to keep the verifier happy. And really all they're doing in their implementation is automatically inserting those type casts for you. So you get the syntactic sugar, or some of it at least, but you don't get any of the execution efficiency. So that's issue number one I have with Java's solution.
In that one paragraph he explins why both C#'s generic collections of reference types and of value types are faster than Java's generics.

Can't Believe (2, Informative)

Apreche (239272) | more than 9 years ago | (#8114193)

People complain about the dumbest things. I always laugh when someone complains about the performance of java. Guess what, if your app needs to be high performance, you shouldn't be doing it in java. If it doesn't need to be high performance but it needs to run on every os and computing device under the sun, then you should use java.

Programming languages are tools. Hammers for nails, screwdrivers for screws, C for hardcore big stuff and python/perl for everyday fun. Java was never intended to be high performance. It was intended to let you run a program on every single device and operating system there is, and have it run almost identically. The fact that java is as high performance as it is now is amazing. If you need performance and java isn't cutting it maybe you should ask yourself "why am I using a screwdriver to put a nail in this piece of wood?"

As for the specific issue of genericising and java's collections. I think java's collections rule. Sure you can't make a collection of primitive types, big deal. You can make an array of primitive types. And you can even make your own class, which inherits from collection and is in fact, a collection of primitive types. But just about everything in java is an Object anyway. So an ArrayList or a LinkedList are good enough 99% of the time. You keep on coding in C#, and when the world doesn't use windows anymore we'll see if your app is still around.

Re:Can't Believe (1)

sfjoe (470510) | more than 9 years ago | (#8114356)

Guess what, if your app needs to be high performance, you shouldn't be doing it in java.

I laugh when people make sweeping generalities that aren't based in reality.

Re:Can't Believe (0)

Anonymous Coward | more than 9 years ago | (#8114464)

agree 110%.

The other downside to java generics is worse (4, Informative)

Matt2000 (29624) | more than 9 years ago | (#8114248)

I read the article to see what the numbers were on performance differences. Turns out there were none, what a surprise! So as usual, in theory, perhaps maybe there might be a performance difference and maybe it might be significant or not, or both. Until real comparisons are made, safe to ignore.

What's more important is his other problem with Java generics which is that in runtime it's not possible to tell what type a collection is compiled as, this is to retain bytecode compatibility. So reflection will have no clue on any of this generics stuff, which isn't a deal breaker, it's just a downside I hadn't heard about before.

Re:The other downside to java generics is worse (1)

thatjavaguy (306073) | more than 9 years ago | (#8116882)

I use both C# and Java everyday and I think that the reflection issue won't hurt many people.

I prefer the Java approach because it means my 1.5 Java code is compatible with pretty much every modern JVM out there.

I'm sick of trying to identify whether I have a user machine with .NET 1.1 or 1.0 on it. I know that my C# code should work on 1.1 and 1.0 but I have far less confidence than (say) running my 1.4 code on a 1.3 JVM. Java gives me a lot more confidence!

Re:The other downside to java generics is worse (1)

tunah (530328) | more than 9 years ago | (#8117706)

It depends on your perspective. Java 1.5 code will run on a Java 1.4 VM (unless it uses some of the new APIs). I can only assume C# won't be able to manage this.

He is wrong... (1)

JMZero (449047) | more than 9 years ago | (#8114311)

Because Java is the best and C# is wrong and if this really is a performance difference then performance doesn't matter today but it probably isn't really a performance difference and what matters is clean syntax and open portability VM I bytecode everybody knows bean he needs to read blah, grouty, blah.

It seems many Slashdot readers not only fail to read the articles or others' comments, but can't even be bothered to read the whole little summary blurb before commenting.

Half the comments on this story are pretty much just template responses to anything that would compare Java and C# - and a good portion of the rest don't seem to have grasped what is stated in the summary.

My theory: posters realize that after the first 50 comments, they'll pretty much be talking to a black hole - so they comment earlier than their comprehension might dictate.

Re:He is wrong... (0)

Anonymous Coward | more than 9 years ago | (#8114537)

[...] bla bla bla [...]

no comments

Oh, the irony! (2, Interesting)

joelparker (586428) | more than 9 years ago | (#8114332)

...we do fairly aggressive code sharing
where it makes sense, but we are also very
conscious about not sharing where you want
the performance.

Welcome to the Microsoft business model. :)

C# vs Java (3, Insightful)

astrashe (7452) | more than 9 years ago | (#8114479)

I've been reading through the various segments of the interview, and I tend to buy most of what Hejlsberg says on various Java vs. C# issues.

But I keep coming back to the idea that the changes (or improvements) aren't enough. If you accept that all of the changes are improvements, that they make things better, they're still not enough to justify getting locked into a single vendor, or in learning new libraries.

C# cleans up some of Java's annoyances, which is great, but the annoyances just aren't big enough to make the shift worthwhile. That's the problem.

I think the libraries problem is huge for Microsoft. The java libraries are just getting to be so big, complex, and rich that it will be very hard to get people to move away from them.

I don't think that anyone says there aren't annoying things in Java, parts of it that wouldn't be done differently if the language could be redesigned from scratch. But those annoyances are liveable -- for the most part, you can deal with them.

Java's has those libraries, though, and one of the reasons the libraries are so rich is that Sun opened up the process to other companies. MS is huge, they have a lot of smart guys, but I just don't think they can compete with Java's comparative openness.

That's the thing -- you can read about checked exceptions, and agree that it would be nice if java handled things more like C#, but it's not even close to being enough to overcome the value of java's openness vs. Microsoft's closed approach.

In the end, it really comes down to the business model.

Re:C# vs Java (1)

sab39 (10510) | more than 9 years ago | (#8115186)

Then take your Java library code, compile it with IKVM [ikvm.net] running on Mono [go-mono.com] , and write code in C# using it without being locked into any vendor :)

Re:C# vs Java (2, Insightful)

astrashe (7452) | more than 9 years ago | (#8116735)

Thanks for the IKVM link. It looks like a pretty cool project, although the blog is a little over my head.

But if I had a job writing software for large banks, or some other very serious group of people (I don't), I'd be afraid of using something like IKVM and Mono -- again, Java's annoyances don't seem annoying enough to push people that far out of the mainstream.

Isn't the primary value of these sorts of projects in the learning?

I mean, in order to follow the IKVM development blog, I'd have to be a much more knowledgable geek than I actually am. I'd be thinking about language syntax, what the compiler is actually doing, and what the VM does in much deeper ways than I do now. Presumably, that would pay big dividends when I regular old java code that would run on the boring old sun jdk.

To me, it seems like knowing this stuff would be a much bigger win than the actual functionality these projects are trying to deliver.

What I'm trying to say is that I have a tremendous amount of admiration for the people who actually build stuff like that, and I wish I was in that league, but I'm not sure that I want to use it.

Re:C# vs Java (1)

sab39 (10510) | more than 9 years ago | (#8117147)

I'm using IKVM in production right now in a real (albeit small) company. And mono plan on releasing 1.0 within the next 6 months, which they will recommend for production use - we're evaluating that for use within our company also.

I have some development tools [nongnu.org] written in Java which have language-independent output (supporting both Java and C#) but our company primarily uses C# these days. Still, every developer had to install the JDK and a JDBC driver in order to run our compile process, since it invokes these Java tools.

These days, I've used IKVM to compile that code to a .NET exe (and the JDBC driver into a dll). Since all our C# developers have the CLR installed by definition, they don't need to install any additional software. This actually happened a little too late because all the developers already had the Java stuff installed, but it'll help when we hire new developers :)

It is true, though, that I've found that following projects like these has helped my ability to write much more boring code. It's also helped when I'm faced with a problem like "hey, we might have a customer who wants to buy our (.NET) stuff but uses primarily Unix, can we help them?" and I can say "Well, it's not 1.0 yet, but there's this project called Mono..."

Can you call C# from C++? (1)

Latent Heat (558884) | more than 10 years ago | (#8119185)

SUN's philosophy is a little bit like "One language to run them all, one language to bind them, one language to link them all . . ." It is kind of like you go whole hog with Java or not at all, and part of the reasoning is that if you link it to other stuff you create platform dependencies.

But Matlab has a cool way of using Java objects, and Java objects have a less-fuss connection to Matlab than MEX-C++. And for tight loops in pure numerical code, Java oddly enough is actually pretty efficient.

JNI also lets you create and operate on Java objects just like Matlab does -- you have to load a VM into your process, but hey, that is what invoking "java myclass" at the command line does. As a vehicle for creating plugins for a C++ program, Java .class files are much more compact than .dll files which tend to link in so much extra . . . stuff.

The JNI is really meant for Java calling into C/C++ to get at some low-level system stuff, but it allows C++ to call Java -- it has to have this capability for the low-level C++ system routine to get stuff back from the Java environment.

Does Mono support C++ calling a C# module? I know there is a MS/VS.NET solution for this, and it is a lot cleaner than JNI. All you need to do is use VS.NET to build an "unmanaged" (i.e. ordinary Windows app) C++ program, and then you need to use some kind of GCHandle template class to take care of the reference into managed code, and then you just invoke methods off that handle as if it were managed C++.

Given that the Mono project doesn't quite have the ambition to make everyone use C# everywhere for every last thing, and given cross-language development (Python-C++, etc) is getting a lot of attention, is there a Mono solution to this? You know, if you could call C# from C++, you could just as well call C# from Python by having a C++ module in the middle. Is there any interest in this capability?

Of what use are generics? (1)

sfjoe (470510) | more than 9 years ago | (#8114780)


I've never used genrics. From what I understand, it's a way to keep a group of different objects in a collection without having to warry about what type of object they are when you retrieve them.
I can't think of any useful application where I need a collection of different types of objects. In some case where I might (a shopping cart) the items can just implement an interface to guarantee me the operations I need to perform on different objects.
Why would I need to collect a String, an int and some user-defined object all in one place? Sounds sort of like the junk drawer in the kitchen that everybody has.

Re:Of what use are generics? (1)

chicogeek (688521) | more than 9 years ago | (#8114852)

You apparently do not understand generics. Generics are not keeping "a group of different objects in a collection". Generics allow just the opposite. Rather than having a container that accepts values of type Object, you specialize a generic container to only accept and return values of your type.

Actually, I was going to give an example, but rather I will instruct people to RTFA.

Re:Of what use are generics? (1)

sfjoe (470510) | more than 9 years ago | (#8114879)



Is that all? Seems like much ado about nothing.

Re:Of what use are generics? (0)

Anonymous Coward | more than 9 years ago | (#8116969)

In java, as soon as you stick something in a collection, you lose all type safety because you have to type cast:
A a = (A)list.get(0);
And since any non-trivial application will use collections, you end up doing potentially unsafe casting a lot. It isn't difficult to avoid the type casting, but it is a pain in the ass to do so.
It might not seem like a big deal to have generics, but it is a much bigger deal when you don't have them and you really need them.

Re:Of what use are generics? (1)

sfjoe (470510) | more than 10 years ago | (#8118963)

In java, as soon as you stick something in a collection, you lose all type safety because you have to type cast:

A a = (A)list.get(0);


I'm still not getting it. It just doesn't seem to be that big of a deal to override the put() method to throw an exception if you try to insert something that doesn't implement your expected interface.
Of course, the rest of the posters to this thread wouldn't have had the opportunity to look down their noses at me and make condescending remarks but that doesn't seem like a design goal the Java folks had in mind.

Re:Of what use are generics? (1)

Bish.dk (547663) | more than 10 years ago | (#8121973)

I'm still not getting it. It just doesn't seem to be that big of a deal to override the put() method to throw an exception if you try to insert something that doesn't implement your expected interface.

True, but this will generate a run-time error, while generics will generate a compile-time error. The run-time error will not be detected until the program actaully executes the code. This may make it necessary to do a lot of tedious testing, and you risk missing some special branch of the program which violates the container's type.

Generics on the other will allow the compiler to detect any attempts to put objects of the wrong type in a container, and thus enable the programmer to detect all errors at compile-time.

Generics are simply safer. I'm definately looking forward to being able to use them in my Java-programs. It is also important to note that you will not be forced to use generics if you don't want to. If you wish to do it the traditional way, you just initialize all your containers with the type Object. This will probably be the default, if nothing else is specified, to maintain backwards compatability.

Re:Of what use are generics? (1)

j3110 (193209) | more than 10 years ago | (#8119306)

First, why are you exposing a collection to any class you don't have control enough over to know what you put in it?

Secondly, the easiest way to protect a Collection is to wrap it. That way you only cast and uncast in one place. It gets inlined, so no performance penalty. It also lets you change the data structure type at will. Say you want to change from a linked list to a dynamic array or a tree. It's simple, and great for fixing performance problems.

I don't recommend implementing the collections interface, unless you have to pass it to some untrusted code that could mangle things and only takes collections.

What you do have to do is create an iterator interface that returns A's instead of Objects. It's really not a whole lot of work, and you can control most of everything that happens. Sometimes you actually need to mess around with objects in a collection, and it beats putting the code around everywhere else.

I think it gives you a lot more flexibility if you do it yourself. If you're worried about having a huge collection, you could have it write the collection to disk and read it in as needed. You could have your own xml-encoder built into your collection. You could implement your own Serializer functions to store the object how you want to as opposed to the built in serializers for the internal types. Say someday you want to convert your collections API to a 3rd party alternative... you'll just have to change a few lines to hit the major points.

I like the control, and since Java is going to inline your functions anyhow, this won't noticably hurt your performance.

Personally, I've used this method to convert between objects being put in and objects being retrieved as well. It makes a good place to perform a two way adapter for your collections. You could implement Collection if you needed.

Re:Of what use are generics? (1)

DrEasy (559739) | more than 10 years ago | (#8121590)

I agree with you, but at the same time it seems to me that generics basically help you avoid all this extra work you're describing, all the while maintaining readability with the syntactic sugar.

However, I sometimes wish Java stopped evolving all the time, it is getting so hard to keep track! We were doing fine without generics weren't we?

Re:Of what use are generics? (1)

The Bungi (221687) | more than 9 years ago | (#8117007)

Write C for five years. Then write C++ for another five with a compiler that does not support generics/templates. No STL, no BOOST, no ATL/WTL, no nothing. Then switch to a compiler that supports them and drool in amazement at how much easier writing code suddenly becomes.

That's not "much ado about nothing", it's just that you don't know what you're talking about.

C# and Java are getting generics because you don't want to spend three days inheriting from DictionaryBase or whatever to crate yet another strongly-typed collection for objects of type 'X'. Amaze at how easier life has become.

Next time I suggest you do some reading on the topic at hand before posting (or post a sensible question instead of a challenge).

Re:Of what use are generics? (1)

aled (228417) | more than 9 years ago | (#8117891)

I don't like the templates/STL combo. I'm not saying it's not usefull, but is too much like a macro mechanism and can be messy. When you make a simple syntax error the compiler messages maybe 5 lines long and not at all clear on what the problem is. And very few people know the internal workings of a STL implementation, and it seems to me that you need to know quite too much to really have control over it. A guy over here that programmed C/C++ for years and use STL didn't know when you need a copy constructor. The documentations and tutorials I have seen over STL are very basic and usually pre ANSI standard. Things doesn't have entity with STL, like string isn't a first class object. As you say after the desert of pure C++ who can refuse the glass of water of any collection library. I think that a lot of C++ programmers that are in awe of STL don't realize that other languages have richer libraries that do a lot more than collection and end doing everything as a collection. Or different paradigms and end thinking of templates as an end and not as a tool.
Just my opinion.

Re:Of what use are generics? (0)

Anonymous Coward | more than 10 years ago | (#8122385)

A guy over here that programmed C/C++ for years and use STL didn't know when you need a copy constructor. The documentations and tutorials I have seen over STL are very basic and usually pre ANSI standard.
First, they guy your are talking about is all too typical. There are far too many people out there who are able to state that they have 10 years of C++ experience, and yet know less about the language than somebody who has studied it for less than a year. It is not hard to learn about the STL. There are several very nice books(Jossutis, and Austern for example) that provide full and in depth coverage.

laziness (0)

Anonymous Coward | more than 9 years ago | (#8114785)

I don't mind it when programmers are lazy during implementation, but during design programmers shouldn't rely on short cuts simply because they are there. I have mixed feelings about generics. Is generics critical? Nope, it really isn't. Can you do exactly the same thing without it? Yes, but a few more lines of code.

In the end, what I like most about java isn't the language itself, but the culture of being verbose and clear about the design and intent. C# is just an updated C++, which is nice, but it retains the same culture. What culture is that? To put it bluntly, it is do what ever you can to get the code done as fast as possible and don't about the design because we will rewrite it anyways. Guess what? from first hand experience, that type of culture leads to software that costs 3x more to maintain than to develop. In the end, you might save a day or two doing it the Microsoft way, but you end up having to spend the same amount of time to fix bugs and add features. How is that suppose to be sustainable or better?

Denmark? (0)

Anonymous Coward | more than 9 years ago | (#8114834)

Just what is it about Denmark? One small little Scandinavian country is responsible for both C++ (Bjarne Stroustrup) and C# (Anders Hejlsberg). Do they have a particularly good education system when it comes to Computer Science or what?

Re:Denmark? (0)

Anonymous Coward | more than 9 years ago | (#8115905)

They're White.

Re:Denmark? (1)

DrEasy (559739) | more than 10 years ago | (#8121607)

Don't forget the language Beta that comes from Aarhus, Denmark.

And of course Lego! If that's not pure Object Oriented thinking, then I don't know what is... :)

Not obviously forcing anything (1)

jpmrst (516393) | more than 9 years ago | (#8116578)

...but perhaps in a future VM version [Java] will allow primitive generics (obviously forcing a bytecode regeneration)

Allowing primitive type arguments in generics would not necessarily require any changes to the VM or bytecode.

The Java 1.5 implementation of generics is substantially based on the Pizza compiler, which allowed primitive type arguments without requiring boxing (links: the pizza compiler [sourceforge.net] , the GJ compiler it evolved into [unisa.edu.au] , some academic papers about the compilers [lamp.epfl.ch] ).

If I remember correctly, the pizza compiler generates separate classes for the different primitive types. It needs a different class loader, but generates classes for an ordinary VM.

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>