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!

Java Generics and Collections

samzenpus posted more than 7 years ago | from the read-all-about-it dept.

Book Reviews 278

andrew cooke writes "Java 6 was recently released, but many programmers are still exploring the features introduced in Java 5 — probably the most significant changes in the language's twelve year history. Amongst those changes (enumerations, auto-boxing, foreach, varargs) generics was the most far-reaching, introducing generic programming in a simpler, safer way than C++ templates and, unlike generics in C#, maintaining backwards (and forwards) compatibility with existing Java code." Read on for the rest of Andrew's review.

Given the history of Generic Java, Naftalin and Wadler's Java Generics and Collections has a distinguished pedigree. In this review I'll argue that this is a new classic.

If you're a Java programmer you've probably heard of generics, an extension to the type system that was introduced in Java 5. They give you, as a programmer, a way to write code even when you don't know exactly what classes will be used.

The obvious example is collections — the author of a List class has no idea what type of objects will be stored when the code is used.

Before generics, if you wanted to write code that handled unknown classes you had to use make use of inheritance: write the code as if it would get Objects, and then let the caller cast the result as necessary. Since casts happen at runtime any mistakes may cause a runtime error (a ClassCastException).

Generics fix this. They let you write code in which the classes are named (parameters) and the compiler can then check that the use of these class parameters is consistent in your program. So if you have a List of Foo instances you write List<Foo> and the compiler knows that when you read that list you will receive a Foo, not an Object.

I'll get to the book in a moment, but first a little history. If you know any type theory — particularly as used in functional languages like ML and Haskell — then you'll recognize my quick description above as parametric polymorphism. You'll also know that it is incredibly useful, and wonder how Java programmers could ever have managed without it.

Which explains why Philip Wadler, one of the people responsible for Haskell, was part of a team that wrote GJ (Generic Java), one of the experimental Java mutations (others included PolyJ and Pizza) that, back in the day (late 90s) helped explore how parametric polymorphism could be added to Java, and which formed the basis for the generics introduced in Java 5.

So if you want to understand generics, Wadler is your man. Which, in turn, explains why I jumped at the chance to review O'Reilly's Java Generics and Collections, by Maurice Naftalin and Philip Wadler.

This is a moderately slim book (just under 300 pages). It looks like any other O'Reilly work — the animal is an Alligator this time. It's well organized, easy to read, and has a decent index.

There's an odd discrepancy, though: Wadler is the generics Guru; this is going to be `the generics reference'; generics are sexy (in relative terms — we're talking Java here) and collections are not; the title has "Java Generics" in great big letters with "and Collections" in little tiny ones down in a corner. Yet very nearly half this book is dedicated to collections.

Generics is a great, practical read. It starts simply, introducing a range of new features in Java 5, and then builds rapidly.

If you are completely new to generics, you'll want to read slowly. Everything is here, and it's very clear and friendly, but there are not the chapters of simple, repeated examples you might find in a fatter book. Within just 30 pages you meet pretty much all of generics, including wildcards and constraints.

If that makes your head spin, don't worry. Read on. The next hundred or so pages don't introduce any new syntax, but instead discuss a wide range of related issues. The chapters on Comparisons and Bounds and Declarations contain more examples that will help clarify what generics do. And the following chapters on Evolution, Reification, and Reflection will explain exactly why.

So the first seven chapters introduce generics and then justify the implementation — any programmer that takes the time to understand this will have a very solid base in generics.

There are even some interesting ideas on how Java could have evolved differently — section 6.9 Arrays as a Deprecated Type presents a strong case for removing arrays from the language. It's a tribute to the clarity and depth of this book that the reader is able to follow detailed arguments about language design. Fascinating stuff.

The next two chapters, however, were my favorites. Effective Generics and Design Patterns give sensible, practical advice on using generics in your work, including the best explanation of <X extends Foo<X>> I've seen yet (so if you don't know what I am talking about here, read the book).

(A practical word of advice — if at all possible, use Java 6 with generics. Java 5 has a sneaky bug).

The Collections part of the book was more along O'Reilly's `Nutshell' lines: the different chapters explore different collection types in detail. I must admit that at first I skipped this — it looked like API docs re-hashed to extend the size of the book.

Then I felt bad, because I was supposed to be reviewing this book (full disclosure: if you review a book for Slashdot you get to keep it). And you know what? It turned out to be pretty interesting. I've programmed in Java for (too many) years, and I guess I've not been quite as dedicated to tracking how the library has changed as I should have been — I learned a lot.

Again, a wide range of readers are welcome. This is more than a summary of the Javadocs, ranging from thumbnail sketches of trees and hashtables to a discussion of containers intended for multi-threaded programming.

The way I see it now, this part is a bonus: the first half, on generics, makes this book one of the standards; the second half is an extra treat I'm glad I stumbled across (I guess if you're some kind of weird collection-fetishist maybe it's even worth buying the book for).

I've used generics since the first beta release of Java 5 and had experience with parametric polymorphism in functional languages before that (in other words, I can tell my co- from my contra-variance). So I guess I'm heading towards the more expert end of the spectrum and I was worried I'd find the book boring. It wasn't. After claiming to be expert I don't want to spoil things with evidence that I'm actually stupid, but reading this book cleared up a few `misunderstandings' I'd had. I wish I had read it earlier.

If you're new to generics, and you don't mind thinking, I recommend this book. If you're a Java programmer who's a bit confused by <? super Foo> then this is the book for you.

The only people who shouldn't read this are people new to Java. You need to go elsewhere first. This is not a book for complete beginners. This is a great book in the classic — practical, concise and intelligent — O'Reilly mould.


You can purchase Java Generics and Collections from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

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

It's only Java 6? (0, Funny)

Anonymous Coward | more than 7 years ago | (#18753255)

I was really hoping they'd make another leap up to Java 60.

Re:It's only Java 6? (0)

Anonymous Coward | more than 7 years ago | (#18753827)

I'm waiting for Java 616.

Propz To Dead Homies yo! (0, Offtopic)

ringbarer (545020) | more than 7 years ago | (#18753269)

A big call out to the guys at Vagina Tech!  Fo'Shizzle!

Re:Propz To Dead Homies yo! (1, Funny)

$RANDOMLUSER (804576) | more than 7 years ago | (#18753353)

It's hard to beleive you're posting at -1

Re:Propz To Dead Homies yo! (0, Offtopic)

Profane MuthaFucka (574406) | more than 7 years ago | (#18753671)

The bat signal is sweeping the skies! Jon Katz, where are you?

C# compatibility? duh... (-1, Flamebait)

Rosco P. Coltrane (209368) | more than 7 years ago | (#18753273)

unlike generics in C#, maintaining backwards (and forwards) compatibility with existing Java code.

Who ever saw a version of a Microsoft product that was compatible with the previous version?

Re:C# compatibility? duh... (1)

ncmusic (31531) | more than 7 years ago | (#18753499)

I don't think there's any merit to that particular statement about backwards compatibility. Can you run you Java 5 code on a Java 2 VM? (They skipped 3, 4 and 5 right?) Generics were released with .Net 2.0. All the the .Net 1.1 code written runs on the 2.0 VM. There wasn't a whole mess of API changes that were obsoleted with the 2.0 it was ehancements to the API and bug fixes. What does forward compatibility even mean?

Re:C# compatibility? duh... (2)

RetroGeek (206522) | more than 7 years ago | (#18754279)

What does forward compatibility even mean?

The hope that deprecated will never happen.

Re:C# compatibility? duh... (1, Insightful)

e2d2 (115622) | more than 7 years ago | (#18753565)

Uhm, can someone explain to me how NEW features of a language can be backwards compatible?

Can I create generics in Java 1.1? If not then how exactly is their generics implementation backwards compatible? Call me crazy but I'm a bit skeptical. I just don't see how this can be done in ANY language. Just because you can run multiple versions of the runtime on the same machine doesn't mean that your new code is backwards compatible.

Re:C# compatibility? duh... (3, Informative)

drooling-dog (189103) | more than 7 years ago | (#18753729)

Uhm, can someone explain to me how NEW features of a language can be backwards compatible?
Ummm... I think it means that programs that were written with previous versions of the language will not be broken by the new version and will continue to run correctly. That's what "backward compatible" has always meant, at least in my lifetime...

Re:C# compatibility? duh... (0, Flamebait)

MobyDisk (75490) | more than 7 years ago | (#18753747)

It's compatible in that you can code something with a Java 5/Java 6 compiler, but is still runs on the Java 4 runtime. This is because they implemented generics as a language kludge rather than a true feature of the runtime. They traded performance for compatibility. Whereas with Microsoft, you can't compile something to use .NET 2.0 generics then run it on the .NET 1.1 framework.

Re:C# compatibility? duh... (1)

Cyberax (705495) | more than 7 years ago | (#18753823)

No, you can't.

If your code uses Java 5 features then it won't run on JDK1.4. You can use tools like Declawer or Retroweaver to run 1.5 code on 1.4 but only to a certain degree.

Re:C# compatibility? duh... (1)

alyawn (694153) | more than 7 years ago | (#18753915)

Right... but you can recompile the source telling javac to produce class files that are 1.4 compatible: `javac -target 1.4'

Re:C# compatibility? duh... (2, Informative)

_xeno_ (155264) | more than 7 years ago | (#18754095)

As soon as you use a generic, the Java compiler requires -source 1.5 and -source 1.5 requires -target 1.5 or higher. So -target 1.4 won't work, even though theoretically generics needn't require 1.5 binaries as all the checking is done at compile-time.

Re:C# compatibility? duh... (1)

Cyberax (705495) | more than 7 years ago | (#18754147)

That won't work if you use new Tiger features. It's just like you're using an older version of compiler.

Re:C# compatibility? duh... (3, Informative)

forgotten_my_nick (802929) | more than 7 years ago | (#18754211)

> If your code uses Java 5 features then it won't run on JDK1.4.

Your wrong. Or at least when it comes to Generics (I haven't tested the rest). Everything is done at the compiler level. So even if you use Generics the code is changed to work in 1.4 if you set javac -target 1.4.

Re:C# compatibility? duh... (2)

CastrTroy (595695) | more than 7 years ago | (#18753885)

I like the way MS implemented their Geneics. Too bad they tie the .Net framework to specific versions of VS.Net. So those of us stuck using VS.Net 2002 don't get to use .Net 2.0. And no, Generics aren't worth the cost of the upgrade.

Re:C# compatibility? duh... (0)

Anonymous Coward | more than 7 years ago | (#18754065)

Use Mono and it runs on other plantforms: don't whine at Microsoft stuff before learning all facts.

Re:C# compatibility? duh... (0)

Anonymous Coward | more than 7 years ago | (#18754153)

You have that backward. VS is tied to a particular version of .Net, not the other way around.
And yes, that does suck.

Re:C# compatibility? duh... (1)

nuzak (959558) | more than 7 years ago | (#18753911)

It's compatible in that you can code something with a Java 5/Java 6 compiler, but is still runs on the Java 4 runtime.

Which happens seldom, because by default the JDK will output a classfile version that older JVMs will refuse to run. People compiling for retrograde targets usually use a JDK from that version too, otherwise they could inadvertantly target standard library API's that don't exist in older versions. Java could make non-erased generics in the future too, just by way of changing the classfile specification and just not erasing them from version 8 on (it's too late for 7). All in all it's mystifying why they did as little as possible with respect to generics, especially in the face of superior generic systems like those in Pizza, other than that they didn't want to disturb the programmers and managers that they believe, by and large, are stupid sheep and easily frightened.

I didn't know that Wadler was behind GJ. I can call GJ's erased generics a kludge, a crock, a hack, a half-assed unsound system, but Wadler really does know his shit.

Erasure isn't the complete end of soundness anyway -- scala generics are erased too, and it still has a far superior type system.

Re:C# compatibility? duh... (4, Informative)

alyawn (694153) | more than 7 years ago | (#18753759)

The language feature of generics *is* new. The compiler can still compile Java 1.1 source and can even compile to older class file versions. The generics implementation is for compile-time type checking, not runtime type checking. The compiled class file has no knowledge of generics.

Re:C# compatibility? duh... (1)

zlogic (892404) | more than 7 years ago | (#18753803)

It probably gets translated into functions that run on older machines. Like C++ macros, templates and inline functions get translated into "pure" C++ code by the preprocessor, or C# 2.0 partial classes are combined together before compilation.

Re:C# compatibility? duh... (1)

twbecker (315312) | more than 7 years ago | (#18753805)

Just because you can run multiple versions of the runtime on the same machine doesn't mean that your new code is backwards compatible.

Uhm, how did this get modded up? Backwards compatability isn't referring to running multiple JVMs. It's referring to the fact that you can write new classes that use generic types and methods, and those classes are still byte code compatible with pre-generic classes. This is because the type checking done by generics is compile time only - typing info is removed from the final compiled class via type-erasure. Asking how something can be true is one thing, asserting it isn't when you obviously have no idea what you're talking about is trolling.

Re:C# compatibility? duh... (1)

Proud like a god (656928) | more than 7 years ago | (#18753813)

I think they mean the Java6 Generics code is compiled to bytecode that will run on previous versions of the JavaVM, in effect allowing you to create Generics in older Java, although I admit I haven't checked this.

Re:C# compatibility? duh... (1, Interesting)

Anonymous Coward | more than 7 years ago | (#18753847)

Simple: in the case of Java Generics, old code can still use generic collections.

So, for example, if you have some old code that adds Strings to a List, you can pass it a List of Integers from new code, and it'll happily add Strings into your generic List of Integers.

A more useful example might be something where old code promises it'll only add Strings so you can pass a generic list of Strings, only to discover at some random point later where the legacy code accidentally added a StringBuffer.

Seriously, though, you can't use generics in pre-1.5 code. Any code that uses generics generates binaries that only work in 1.5 or later JVMs. (Despite the fact that generics are compile-time only.) The only "backwards compatible" part is that pre-1.5 code will still compile and pre-1.5 binaries will still run. As I've suggested above, though, that backwards compatibility completely defeats the purpose of generics.

Which isn't to say they're completely useless, but they're essentially no more useful than a simple comment to indicate what the programmer wants the collection to contain rather than what it actually contains. Especially when legacy code is involved.

Re:C# compatibility? duh... (2, Interesting)

Cyberax (705495) | more than 7 years ago | (#18753869)

It means that you can create List<String> and pass it to a legacy method which takes only unparameterized List. Or you can get unparameterized List and cast it to parameterized type.

It's impossible to do in C#/C++.

Re:C# compatibility? duh... (0)

Anonymous Coward | more than 7 years ago | (#18753879)

You can compile code that uses generics and run it on older versions of the virtual machine, that is, the bytecode implementation of generics looks like regular, pre 1.5 bytecode

Re:C# compatibility? duh... (1)

FunkyELF (609131) | more than 7 years ago | (#18753959)

They can do this because all checking is done at compile time. No features were added to the runtime to get this.

Once compiled into bytecode a Vector>> looks just the same as a regular vector of objects and the compiler takes care of all the casting for you.

No more
int i = ((Integer)((Vector)((Hashtable)vec.get(3)).get("wo w")).get(2)).intValue();
Just
int i = vec.get(3).get("wow").get(2);

Well, this example used the auto-boxing feature too to convert the Integer to an int.

Re:C# compatibility? duh... (1)

FunkyELF (609131) | more than 7 years ago | (#18754001)

Replying to self....Should have used preview.... my <'s and >'s didn't show up right in the text.

It should have said ...

Once compiled into bytecode a Vector<Hashtable<String,Vector<Integer>>> looks just the same as a regular vector of objects and the compiler takes care of all the casting for you.

Re:C# compatibility? duh... (1)

Pxtl (151020) | more than 7 years ago | (#18754245)

Yep. I was extatic when C# got generics... for a while - but pretty quickly you start runnign into their limitations (or at least the limitations of the standard ones).

For example, you want a class that contains a list - you get to look forward to either (a) reams of boilerplate code as you forward all the methods of the list that an outside user might need, or (b) publicizing the list and completely mucking up your class invariants.

Plus, no typedef, so get, nested> class, declarations> - twice if you need a constructor. And Using statements are not a substitute unless you write your whole project in a single .cs file.

A lot of coders use subclassing instead of typedef, but that opens a new can of worms - forwarding constructors, destroying the substitutability of the class, etc.

Re:C# compatibility? duh... (1)

Pxtl (151020) | more than 7 years ago | (#18754345)

Ick, pwned by the same mistake as parent poster. I meant some<nonsense<rather, like>, this>.

Re:C# compatibility? duh... (1)

heffrey (229704) | more than 7 years ago | (#18753579)

Office 97/2000/XP/2003/2007, for example. I take it you've never used MS software.

Re:C# compatibility? duh... (4, Insightful)

JebusIsLord (566856) | more than 7 years ago | (#18753693)

Man, that is just not fair. Microsoft has been burdened with backwards compatibility like no other company out there. I mean, except on 64-bit Vista, you can still run 16-bit DOS apps in the latest release of Windows, 20+ years later! Try running a circa 2001 OS9 app on a new Mac, and let me know how that goes for you. Microsoft has been hamstrung by their commitment to backwards compatibility; I am convinced that (and bad management) are the reasons for Vista's mediocrity. Yeah, some stuff broke, but I wish they'd broken more in the pursuit of a "good" OS.

On topic, C# 2.0 was introduced with .NET 2.0, which included bytecode optimizations that aren't backwards-compatible. The generics stuff probably could have been, but meh; Microsoft controls the only real .NET platform anyhow. Its not like they had to remain compatible with mobile phones and such, like Sun did.

Re:C# compatibility? duh... (1)

laffer1 (701823) | more than 7 years ago | (#18754047)

While you are mostly correct, Microsoft has been removing compatibility features in newer versions of Windows. OS/2 and POSIX subsystems present in Windows 2000 and Windows NT were removed for Vista. Actually, one of them was removed in XP SP2.

There is nothing wrong with offering compatibility. Microsoft's approach to compatibility needs to change a bit. Separating the legacy system from the modern system should be more exact like Classic support in OS X (pre intel). Really old apps ran in a sandboxed OS9 install. (non carbonized) Microsoft could even go a step farther by working on something with Virtual PC. They could provide a built in DOS/9x compatibility system with say directx 5 support. That would allow most really old stuff to run while they trim some of the fat from the current winapi.

Re:C# compatibility? duh... (1)

fireboy1919 (257783) | more than 7 years ago | (#18754237)

but meh; Microsoft controls the only real .NET platform anyhow

This is what makes it so utterly astounding to me that a great many of the standard libraries that Microsoft pushed on everybody for .Net 1.1 are replaced with something else entirely in 2.0.
They didn't even bother with a deprecation phase - just gone.

So not only will code compiled for .Net 2.0 not necessarily work on 1.1 - code written for 1.1 will not necessarily work for 2.0.

You have to manually check which version you're running and run different segments of code to do certain tasks.

That's why I think of .Net code as being a lot like Java code, except probably not portable between VMs.

Re:C# compatibility? duh... (0)

Anonymous Coward | more than 7 years ago | (#18754303)

That doesn't sound right to me. Can you give me some examples?

Re:C# compatibility? duh... (1)

JebusIsLord (566856) | more than 7 years ago | (#18754425)

Totally not how it works. You can (and should) install both 1.1 and 2.0 concurrently, and the bytecode runs on the vm it was compiled for. Problems averted.

Re:C# compatibility? duh... (1)

Jugalator (259273) | more than 7 years ago | (#18754257)

Microsoft has been hamstrung by their commitment to backwards compatibility; I am convinced that (and bad management) are the reasons for Vista's mediocrity. Yeah, some stuff broke, but I wish they'd broken more in the pursuit of a "good" OS.

The sad part of this story was that the pursuit of a better OS was scrapped. Longhorn was more than a mere codename; it was a radically different vision than what Vista ended up as. I can only imagine the frustration at Microsoft as they had to make that decision. They lost more than WinFS in the process, that's for sure.

Re:C# compatibility? duh... (5, Insightful)

Hikaru79 (832891) | more than 7 years ago | (#18753835)

Who ever saw a version of a Microsoft product that was compatible with the previous version?

Are you joking? I hope you're joking. Because the alternative is that you are being criminally thick. I really think Slashdot should have a mod option -1 Misinformed

Say what you will about Microsoft, but backwards compatibility has always been one of their cornerstones. Their compatiblity layers still allow you to run apps from the early 90's on a modern copy of Vista today. I have managed to get some very old VB3 code working with a minimum of modification on VB6, which then, using Project Analyzer, got compiling in .NET in a matter of (admittedly frustrating) days.

And who are you comparing them with? Linux? You must be joking. Linux has trouble (read: is completely unable to) maintain binary compatibility with even relatively recent "old" code because of changing libc versions, etc.

Please, name ONE other operating system out there that can claim to run decade-old binaries flawlessly in its most recent incarnation.

Disclaimer: I'm a dedicated FOSS user and not a Microsoft shill in any way. But please, let's give credit where credit is due.

Re:C# compatibility? duh... (1)

wezeldog (982156) | more than 7 years ago | (#18754363)

OS/400. I believe it ran system/36 code. When they switched to PowerPC, programs 'converted' to 64-bit on the fly thanks to TIMI. Hope this helps.

Re:C# compatibility? duh... (1)

Helios1182 (629010) | more than 7 years ago | (#18754441)

Some IBM mainframes such as the zSeries still run System 360 code unmodified. That is 4 decades right there.

And modded up, too (1)

dedazo (737510) | more than 7 years ago | (#18753997)

That's clever, yes. I suppose there has to be one of these in every "discussion". Thanks for increasing the signal-to-noise ratio and all that.

Generics are basically good. (4, Interesting)

Z00L00K (682162) | more than 7 years ago | (#18753387)

But it can in some cases be tricky when you get a really complex structure of Vectors containing Vectors containing Comparables. Not that it's impossible, but it can be a challenge.

One thing that I found in Java5 was that it lacked generics for several cases, e.g. Awt/Swing objects that were able to contain Object themselves. Not that it was a big problem, but it wouldn't have been bad to have that support there too...

Anyway - Generics is one of the best features of added to Java lately. It really helps. How I miss it when I'm programming for J2ME...

Re:Generics are basically good. (1)

Kobayashi Maru (721006) | more than 7 years ago | (#18753725)

I've had trouble with generics myself. I don't claim to be a programming superstar though, so I might be overlooking something simple. My problem is that I cannot get a (useful) array out of a vector. No matter what I do, Vector.toArray() will only return an array of Objects. But I don't want Object[], I want something specific. And I thought that is what generics were supposed to do: declare a vector, use generics to tell Java what kind of objects are in it, and get rid of all those nasty casts. Unfortunately, this doesn't seem to be the case. It seems that the information is lost at runtime, do to what Google tells me is "type erasure." There is an open bug [sun.com] on the subject, which I think is related. Regardless, I find it rather annoying and cumbersome to work around.

Re:Generics are basically good. (1)

bunratty (545641) | more than 7 years ago | (#18753815)

It's been years since I've written Java, but
SpecificClass[] sca = scv.toArray(new SpecificClass[0]) [sun.com] ;
should do it, right?

Re:Generics are basically good. (1)

twbecker (315312) | more than 7 years ago | (#18753855)

I wouldn't hold your breath if you're waiting for a deprecated class like Vector to get retrofitted with generic methods.

Re:Generics are basically good. (1)

bunratty (545641) | more than 7 years ago | (#18753935)

As I show above, it already has been. In fact, being an AbstractList, it must have generic methods.

Re:Generics are basically good. (1)

twbecker (315312) | more than 7 years ago | (#18754039)

I stand corrected. My intent was more to prod the OP into moving away from using Vectors, but that information is valuable nonetheless.

Re:Generics are basically good. (1)

MCTFB (863774) | more than 7 years ago | (#18753857)

Generally, the way you do this (with or without generics), is to call the toArray(Object[] array) method, rather than the toArray() method.

Basically, just do this where foo is the type in the array and fooList is your Collection of Foo objects.

Foo[] foos = new Foo[fooList.size()];
fooList.toArray(foos);
The foos array now is populated with the contents of the fooList.

The toArray() will return an array of type Object, so you will need to use the argument supplied version of the method if you want the component type of the array to be a particular type.

Re:Generics are basically good. (1)

roscivs (923777) | more than 7 years ago | (#18753917)

But it can in some cases be tricky when you get a really complex structure of Vectors containing Vectors containing Comparables. Not that it's impossible, but it can be a challenge.

The problems with Comparables usually come about because of a failure to implement Comparable instead of just implement Comparable. Java typically won't tell you that's the problem, it will steer you off into some other wild goose chase, but if you implement Comparable the challenges typically disappear.

All I really wanted... (3, Interesting)

Lockejaw (955650) | more than 7 years ago | (#18753389)

... was a quick and dirty intro to Java generics. I've had trouble finding that on Sun's site (especially ones with good code examples), but Google returns some good results. Given the availability of free tutorials, I probably wouldn't buy the book just for that.
That said, this sounds like a good resource on Java Collections in general (though Sun's javadocs are pretty nice themselves), as well as the other features introduced in Java 5. There also seems to be some discussion of more complex generic structures.
I'm still a bit lukewarm about buying it, but if I were getting back into a lot of Java stuff, I probably would.

Re:All I really wanted... (1)

metamatic (202216) | more than 7 years ago | (#18754325)

http://java.sun.com/j2se/1.5/pdf/generics-tutorial .pdf [sun.com]

http://java.sun.com/docs/books/tutorial/extra/gene rics/index.html [sun.com]

Also highly worthwhile is http://java.sun.com/docs/books/tutorial/collection s/index.html [sun.com] which describes the generics-enabled standard collection classes, which is 90% of what you'll want generics for anyway.

Share and enjoy.

Java 'generics' are not real generics (5, Informative)

Cyberax (705495) | more than 7 years ago | (#18753445)

Java generics are not real generics, then you parametrize a generic class in Java you don't really create a new type. You just attach some information for Java compiler so it can perform automatic casting and save you some typing.

Java generics don't provide real type safety, for example, you can easily put Strings in List (that's why Collections.checkedCollection kludge was added).

In C# (or C++), on the other hand, parameterizing a generic type creates a _new_ _type_ which guarantees type safety and allows some quite interesting tricks. For example, in C# generics can be parametrized by primitive types and structs (which don't exist in Java, anyway) so you can have List without overhead of boxing. That's impossible in Java.

Re:Java 'generics' are not real generics (2, Informative)

Cyberax (705495) | more than 7 years ago | (#18753553)

Sorry, Slashdot ate "<" and ">".

"you can easily put Strings in List" should be "you can easily put Strings in List<Integer>".

"so you can have List without overhead of boxing" should be "so you can have List<Integer> without overhead of boxing"

Re:Java 'generics' are not real generics (1)

KillerCow (213458) | more than 7 years ago | (#18753761)

you can easily put Strings in List<Integer>


Really? I would like to see the code which does this without generating a warning.

Re:Java 'generics' are not real generics (1)

jfengel (409917) | more than 7 years ago | (#18753993)

This code generates no warning for me (I'm using Eclipse rather than the JDK, so YMMV):

List s = new ArrayList();
List l = s;
l.add("foo");

Further, if you do:

Integer i = s.get(0);

you get a runtime class cast exception.

Re:Java 'generics' are not real generics (1)

Sneftel (15416) | more than 7 years ago | (#18754093)

What jfengel meant to say was:

List s = new ArrayList<Integer>();
List l = s;
l.add("foo");

Re:Java 'generics' are not real generics (1)

jfengel (409917) | more than 7 years ago | (#18754271)

Argh. Thank you. It's not very interesting without the generics.

I'd also meant to add the generic to the definition of s, so that it should be:

List<Integer> s = new ArrayList<Integer>();

So when you pull the element out:

Integer i = s.get(0);

it can be done without an explicit cast. But the cast occurs anyway and generates a ClassCastException if you've put a non-Integer into the array. That's far later than it ought to be; the error occurred long ago and far away, so debugging it can be a real pain.

Re:Java 'generics' are not real generics (2, Interesting)

harves (122617) | more than 7 years ago | (#18754351)

What compiler are you using??

harvey@clownfish:~$ cat test.java
import java.util.*;

public class test
{
      public test()
          {
                List s = new ArrayList<Integer>();
                List l = s;
                l.add("foo");
          }
}
harvey@clownfish:~$ javac test.java
Note: test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
harvey@clownfish:~$ javac -Xlint:unchecked test.java
test.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
                l.add("foo");
                          ^
1 warning

Re:Java 'generics' are not real generics (1)

edishere (1089121) | more than 7 years ago | (#18754285)

Ummm.... you are just using autoboxing here, not generics.
You should try:
List s = new ArrayList();

then you CAN do:
List l = s; .... but I don't know why you ever would, and if you decided to do that you could THEN do:

l.add("wow");

and you get errors. Sure, if you use goto's wrong you can get errors, if you use unsafe regions in C# incorrectly you can get errors, but then again, you are not using the language as intended.

if you did:
List s = new ArrayList(); ... and then:
s.add("wow");

you get what you would expect, a compilation error.

Re:Java 'generics' are not real generics (1)

jfengel (409917) | more than 7 years ago | (#18754501)

If you reread your post as posted, you'll see you made the same mistake I did: Slashdot took the angle-brackets and treats them as HTML tags rather than as Java code. I was in fact using generics, but they disappeared in the Slashdot posting process. The same thing happened to your post.

If you put back the generics in both your post and mine, as somebody corrected for me in a sub-post, I think you and I are talking about the same thing.

I don't know why somebody would cast a List<Integer> to a plain List, but it's legal, and that's a problem that other parameterized languages don't have. But doing it that way preserved a lot of other nice features of the Java Virtual Machine, and with the right warnings turned on the compiler can spot it as a probable error, so I'm not really complaining. I'm just concurring with an ancestor-post that Java's generics don't truly introduce new types but are instead merely a compile-time hack.

Re:Java 'generics' are not real generics (1)

Cyberax (705495) | more than 7 years ago | (#18754075)

void doSomething(List lst)
{
      lst.add("Hello, world!");
}

List<Integer> intList=new ArrayList<Integer>();
doSomething(intList);

assert(intList.get(0) instanceof Integer); //Oops!

Re:Java 'generics' are not real generics (1)

CastrTroy (595695) | more than 7 years ago | (#18753713)

Am I the only one who tries to do away with arrays whenever possible? Sure I use them in some cases, but their limited ability to resize is something I find to be a real issue. With Lists and Generics, I find I'm using Arrays less and less, even in cases where an Array would probably work, just because lists offer so much more functionality.

Re:Java 'generics' are not real generics (3, Informative)

Jeffrey Baker (6191) | more than 7 years ago | (#18753767)

Sure, Java generics work at compile time instead of runtime. At runtime, you can do whatever you want. But it's still true that Java generics provide a much safer interface which prevents a wide field of bugs, and which makes code much more readable. I think it's obvious that

l = new List();
l.add(foo);
Foo foo = l.get(0);

is much safer and easier to read than

v = new Vector();
v.add(foo);
Foo foo = (Foo) v.get(0);

especially when you consider that the obvious mistake

v = new Vector();
v.add(bar);
Foo foo = (Foo) v.get(0);

throws a cast exception at runtime.

I've read a lot of complaints that type erasure (the means by which Java generics are implemented) doesn't solve the whole problem. But there was a certain class of program that generics solved, and it has made development in Java much more productive and safe.

Re:Java 'generics' are not real generics (1)

Cyberax (705495) | more than 7 years ago | (#18753897)

Yes, I absolutely hate to maintain old pre-1.5 code because generics make it so much easier to use.

But the problem is that generics could be implemented in a much better way, C# proves that.

ATTN: SWITCHEURS! (-1, Troll)

Anonymous Coward | more than 7 years ago | (#18753921)

If you wish Xcode would reformat your code for consistency, GTFO.
If you're overwhelmed by IB's multi-paletted interface, GTFO.
If you've ever typed a backslash outside of ASCII art, GTFO.
If you can't intuit your way from HyperTalk to AppleScript, GTFO.
 
Bandwagon-jumpers are not welcome among real [imageshack.us] Mac [imageshack.us] geeks [imageshack.us] . Keep your filthy PC fingers to yourself.

Re:Java 'generics' are not real generics (1)

twbecker (315312) | more than 7 years ago | (#18753989)

Sure, you can put Strings in an Integer collection, but you'll get a warning at compile time about using a raw type. The alternative, is to create a new type, lose all your backwards compatibility, and force folks to upgrade their entire codebase when moving to Java 5. Personally, I think what was done was a reasonable compromise.

Re:Java 'generics' are not real generics (4, Informative)

roscivs (923777) | more than 7 years ago | (#18754005)

Java generics don't provide real type safety, for example, you can easily put Strings in List (that's why Collections.checkedCollection kludge was added).

I've never understood this objection. This will always generate a compiler warning, and depending on your compiler settings may not even compile successfully. The only time you might turn those warnings off is when you're having to deal with non-genericized legacy code.

Re:Java 'generics' are not real generics (1)

rtssmkn (900096) | more than 7 years ago | (#18754061)


The part about auto-boxing is generally not true, especially when it comes to low-level generic interface method invocation.

See http://msdn.microsoft.com/msdnmag/issues/1200/dotn et/ [microsoft.com] for a short instruction on how primitive types directly map to
objects in the language, the very same concepts of auto-boxing and unboxing take place as they are implemented in the Java
language.

Re:Java 'generics' are not real generics (1)

Cyberax (705495) | more than 7 years ago | (#18754207)

Please, read about generics in C# and value type usage in generic code. You can create generic collections of value types without overhead of boxing.

For example, here: http://www.artima.com/intv/generics2.html [artima.com]

Re:Java 'generics' are not real generics (0)

Anonymous Coward | more than 7 years ago | (#18754491)

Bah. Next you're going to be telling me Lisp had this 20 years ago, except with a native compiler, and that even C#/C++ generics are somehow worse because they don't have multiple-dispatch.

Attention nerds (-1, Flamebait)

Anonymous Coward | more than 7 years ago | (#18753455)

Whichever one of you resentful videogame addicted loners shot up the Virginia Tech campus a little while ago, that was a real dick move you guys. Just stop it.

I don't think he can see this (-1, Offtopic)

Anonymous Coward | more than 7 years ago | (#18753627)

Since he's dead, too.

Too bad Java generics are completely useless (2, Informative)

Anonymous Coward | more than 7 years ago | (#18753489)

Amongst those changes (enumerations, auto-boxing, foreach, varargs) generics was the most far-reaching, introducing generic programming in a simpler, safer way than C++ templates and, unlike generics in C#, maintaining backwards (and forwards) compatibility with existing Java code.

Yeah, and by maintaining that backwards compatibility, they became totally worthless.

The only thing it offers is some compile-time sanity checking, but even that can be disabled through use of a new compiler pragma directive to suppress warnings. In fact, in several cases, you HAVE to disable warnings because certain operations (like creating an array of a generic type) are impossible without a warning.

Ever wondered why the collection classes require you to pass in an array to the toArray(T[]) method? Because Java generics throw away the class information after compile time (although there's no reason they need to do this, they could have kept it and maintained backwards compatibility), so you have to pass in an array to give the type information Java removed.

Java generics could have been useful, but since casting them into a non-generic type generates an ignorable warning, they become worthless. It's only a few lines of code to place a Double into an Integer collection, thereby removing then entire point completely.

Re:Too bad Java generics are completely useless (4, Insightful)

LarsWestergren (9033) | more than 7 years ago | (#18754409)

The only thing it offers is some compile-time sanity checking, but even that can be disabled through use of a new compiler pragma directive to suppress warnings.

Many operations are ERRORS, not warnings. This is caught by IDEs, and by the compiler.

In order to make it possible to interact with legacy code, you can pass a generified collection to a method that expects a "raw" collection. This gives you a very clear warning. So for 95% of all use cases, generics give you a lot of assistance. You manage to come up with a remaining 5% example, where a programmer casts, suppresses compiler warnings, and then passes in a object of the wrong type, and this makes generics worthless?

Wadler was involved with the design of Haskell, and he and people like Gilad Bracha designed Java generics. I trust their skills more than a Slashdot Anonymous Coward.

All Roads Lead to Rome (-1, Offtopic)

Tablizer (95088) | more than 7 years ago | (#18753589)

To do flexible programming and to remove excessive code duplication you generally need some form of "meta programming" where programs can create, see into, or alter themselves to some extent. However, if you do this on a larger scale, you basically are creating a roll-your-own database. Thus, I think that one should perhaps look at better integration with and/or hooking a database to the app language. For example, storing function names in tables rather than using case statements or polymorphism. That way you don't need explicit in-app lists that have to mirror table rows. Java developers seem to be afraid of the database rather than embracing it. I think Java books overemphasize DB vender swappability. It is just not that important in most shops (yes, there are excpetions) and creates duplicate "mirror" structures that bloat up code and make busy work. I think relational databases are potentially better tools to manage and study complex collections/structures than in-app structures. (I say potentially because existing RDBMS are not fully designed for such a task.) In short, the real answer is to merge with and embrace DB technology, blurring the distinction between database and app. It may also make for more flexible code management than hierarchical file systems anyhow. Hierarchies have reached their limit in my opinion. We need queries and set theory to move to the next level in my opinion. Code is growing too unruly for hierarchies and static structures to handle.

Re:All Roads Lead to Rome (2, Informative)

Cyberax (705495) | more than 7 years ago | (#18753715)

Unworkable. Polymorphism and ifs/switches are SEVERAL ORDERS OF MAGNITUDE faster than database access. So it's better to keep them separated.

As for metaprogramming - you can look at Nemerle (http://nemerle.org/Main_Page) which excels at metaprogramming. It's one of the best languages I've seen.

But there's research in bridging the gap between databases and code - see http://en.wikipedia.org/wiki/Language_Integrated_Q uery [wikipedia.org] for an example.

Reading Generified Code Makes My Brain Hurt (2, Interesting)

MCTFB (863774) | more than 7 years ago | (#18753651)

I don't use any of the generic syntax at all in my code as I feel it makes it virtually unreadable to other developers. The syntax is just absolutely horrible, plus as most adept Java programmers know (been coding in Java myself since 1.0), the way generics is implemented in Java is broken (depending on your point of view on this matter).

Then there is the Collections API itself which upon first glance seems like it was written by amateurs who have never had to write any performance critical code in their lives. For this reason as well, I generally try and avoid using anything in java.util as well.

And now they are talking about adding closures (more bloat) to Java which as I understand the proposal will be implemented under the hood in basically the same way as inner classes (another feature that is a maintenance nightmare that gets abused by novice developers ad infinitum).

Is Java not bloated enough? Do the guys at SUN have such feature envy of C# (the bastard child of Java), that they can't just say enough is enough?

I feel like this is all coming full circle with C++ in the sense that Java now has so many language features that it is becoming too complicated for entry-level developers to be truly productive with and now a new language is needed that has the best features of Java, minus all the bloat that totally overwhelms the initiates.

With more features, generally comes more power, but with more power there is more room for abuse for those who don't have the wisdom to use it (i.e. newbies). Everyone in programming starts off as a newbie and needs to get their feet wet, but once you make a programming language where everyone has a light saber, but does not have the Jedi training or wisdom to use it, well then you are going to have a lot of people causing a whole lot of trouble.

One of the main reasons why Windows software development has slowed to a crawl (besides of course the cannibalizing nature of MS on the Windows platform), is that it takes a good 4 years or more of full-time experience with the Windows API's just to become adept at programming on that platform, on top of being decent at C/C++ itself. I know Microsoft has tried to reduce that learning curve with C# and .NET, but nevertheless the learning curve is still huge. With Java, the same thing is happening. What was once a simple, yet powerful programming language has evolved into a monster on par with the same kind of crap that comes out of Redmond that is overengineered and the last thing from elegant.

I guess it is time for a new application programming language.

Re:Reading Generified Code Makes My Brain Hurt (3, Insightful)

Cyberax (705495) | more than 7 years ago | (#18753787)

Bullshit.

Generics syntax is quite readable and easy-to-use, especially with good IDE support. And generics certainly make the code more readable because the add type information.

Foreach loops, varargs and autoboxing is just a minor syntax sugar, nothing really big.

I've used a lot of collection frameworks in a lot of languages (and even wrote my very own vector and string for C++), Java Collections Framework is quite OK. It's not hard and reasonably fast.

Re:Reading Generified Code Makes My Brain Hurt (0)

MCTFB (863774) | more than 7 years ago | (#18754025)

an IDE should not be a requirement for any programming language just to write "Hello World".

Re:Reading Generified Code Makes My Brain Hurt (1)

Cyberax (705495) | more than 7 years ago | (#18754255)

You can use generics without IDE. I do it all the time for small fixes when I don't want to setup a project in IDEA.

There's nothing complex in adding a type parameter in angular brackets.

Re:Reading Generified Code Makes My Brain Hurt (0)

Anonymous Coward | more than 7 years ago | (#18754055)

Welcome your python overlords with open arms

Re:Reading Generified Code Makes My Brain Hurt (1)

marcosdumay (620877) | more than 7 years ago | (#18754361)

Exactly. Since I've met Python I can't help not thinking it is the VB killer.

What creates a lot of problems for the language on my point of view, but I was never the target audience of any of those languages.

Re:Reading Generified Code Makes My Brain Hurt (0)

Achoi77 (669484) | more than 7 years ago | (#18754333)

Then there is the Collections API itself which upon first glance seems like it was written by amateurs who have never had to write any performance critical code in their lives.

forgive me for being ignorant, but I haven't really found anything wrong with the Collections API. I found them to be pretty useful and saves a big of time from having to redo the wheel on each project I come across.

performance is a funny word. To some performance is depending on how much raw speed you can crank out of those transistors; to others it's simply looking at the Big O notation. I think Sun looks at the Big O and assumes the user will be responsible for taking care of the rest.

A slightly humorous quote I read on about an interview/talk someone had with the people from a online game (based on the hardware mention you can probably guess which one):

In the center they run a central database that they have pushed to the maximal edge by throwing Big Hardware at it (millitary spec TI RAM hard disks for instance.) Their only answer to future scaling was "well Moore's law has saved us so far..."

Not to be bashing the developers above as I am certainly in no position to talk, but if you truly are relying on trying to get bleeding edge performance by using optimizing techniques and throwing bigger hardware at it in order to catch up to the scaling necessary to maintain a certain qos, then perhaps it really is time to step back and really take a look at the overall scheme, even if it really means starting from scratch.

now, whatever that means from a business sense, it's a completely different matter...

Re:Reading Generified Code Makes My Brain Hurt (1)

harry666t (1062422) | more than 7 years ago | (#18754443)

> I guess it is time for a new application programming language.

How about a mix of COBOL, brainfuck and swahili?

Re:Reading Generified Code Makes My Brain Hurt (2, Informative)

LarsWestergren (9033) | more than 7 years ago | (#18754475)

Do the guys at SUN have such feature envy of C# (the bastard child of Java), that they can't just say enough is enough?

Sun does not control the development of Java, the Java Community Process does. And it is not C# that is seen as a threat I believe, but Ruby and functional languages. There is a VERY heated debate in the Java community over the new language features that are proposed for the Java platform, and both sides put up some very convincing arguments (simplicity is good vs a language needs to evolve, for instance). See for instance the different Closures proposals...

Generics, jeez (1, Interesting)

kahei (466208) | more than 7 years ago | (#18753839)

The original post is being just a little specious on generics -- the reason Java generics are backwards compatible is that they aren't generics, they're just automatic type conversions when accessing collections. Whee. C# generics may not be up to the level of true generic programming (e.g. C++) but they are at least 'templates' in the sense that ArrayList is a different type from ArrayList.

Java has come a long way but there's still a reason Java programmers cost about 60% of the cost of actual C++ programmers (curse them).

Sticking to Java 1.4.2.x (0, Troll)

roman_mir (125474) | more than 7 years ago | (#18753851)

There was a time when I actually was hoping to move from Java 1 to 1.1 and then later from 1.1 to 1.2 The move from 1.2 to 1.4 was still a good thing. However after trying Java 5 and 6 I refuse to move away from 1.4 I do not feel the need to move from something that works to something that pretends that it does more than it really does and introduced an entire set of problems on the way. As far as I am concerned the language is already bloated. I would love to see Java drop inheritance off entirely (and I have used it correctly too,) but there is no need for it really. Everything can be done with interfaces and libraries. From what I see the game is not really concerned with 'correct' implementations of pure coding paradigms, but it is rather concerned with good easily maintainable solutions where the mix of developers mostly consists of below average coders. Oh, and bringing varargs into a language? Talk about shooting yourself in the foot.

Re:Sticking to Java 1.4.2.x (1)

MCTFB (863774) | more than 7 years ago | (#18754083)

I agree mostly, though varargs I have found to actually be very useful in a few cases where it can greatly improve readability. (though due to the reflection aspect of how varargs works under the hood, they should never be used in performance critical code). As for everything else, well yah it is just syntactic sugar.

Unfortunately, lazy or newbie programmers will use autoboxing and varargs more than just sparingly and being the second generation coder on a project where these features are used liberally is a hell I would not wish on my worst enemy.

Re:Sticking to Java 1.4.2.x (1)

Cyberax (705495) | more than 7 years ago | (#18754289)

Sorry, but that means you don't want to learn new things.

Generic code is much easier to maintain and read because you have MORE type information. Another changes like foreach loop and varargs are just syntax sugar and do not deserve more than a few minutes of attention.

Two words: Type erasure (4, Informative)

BitwizeGHC (145393) | more than 7 years ago | (#18753947)

Java generics are kept back-compatible with the old VM spec by way of type erasure: parametric information is "erased" from the type when it is compiled. So List and List and List all compile down to the same type: List.

Among other hiccups this makes it impossible to overload methods whose argument types differ only in the parametric information included with them.

By contrast, C++ templates and C# generics create a type disjoint from all other types in the same type class for each set of parameters in the type declaration.

Yet another sterling example of Java lossage.

Two words: Bracket erasure (4, Informative)

BitwizeGHC (145393) | more than 7 years ago | (#18753977)

Sentence in the above post should have read as follows:

So List<String> and List<java.math.BigInteger> and List<javax.swing.JComponent> all compile down to the same type: List.

Re:Two words: Type erasure (1)

MCTFB (863774) | more than 7 years ago | (#18754169)

Hey if you like 23234290234^345 sized megabyte applications where most of the program memory is used up by a bunch of redundant templates, then more power to yah (-:

Java-only programmers? (2, Insightful)

mr_mischief (456295) | more than 7 years ago | (#18753951)

Wouldn't someone have to be used to _only_ Java to not be familiar with at least some of these concepts?

Enumerations are available in Pascal and pretty much all of its descendants IIRC. It's also a type of field in an SQL database for much the same purpose as enumerations in programming languages.

The foreach loop has been in Perl since 2.0 in 1988. C# got foreach in 2000. It's in PHP. It comes from earlier FOR..IN loops from shells.

I'm sure there are examples of the other features which are similar to the Java version of them. The syntax may be different, and the exact details of darker semantic corners may be different. The concepts, however, are pretty easy to have run across unless someone has only used the one language.

The review seems to imply that bringing in what has been proven to work well in other languages is too confusing and should be done at a slower pace. The truth is, people program in a subset of any general-purpose language at first, and that subset grows over time. If someone works with code from other programmers, one picks up the parts of the language to which they are exposed as they are exposed to them. No one needs to cram all night to be up on all the new features of a language the day after the manual gets updated.

warning: nitpicks ahead (2, Informative)

PhrostyMcByte (589271) | more than 7 years ago | (#18753991)

introducing generic programming in a simpler, safer way than C++ templates and, unlike generics in C#, maintaining backwards (and forwards) compatibility with existing Java code."

*prepares to be modded troll*

People need to stop comparing Java/C# generics to C++ templates - they take similar syntax, but they aren't the same thing. I'm not sure how one can even be safer than the other.

And C# 2.0 maintained compatibility with existing C# 1.0 code (you still have access to the old containers) while actually giving significant performance benefits where Java is only syntax sugar that still produces the same old slow code.

Re:warning: nitpicks ahead (1)

jinxidoru (743428) | more than 7 years ago | (#18754437)

This is so true. Although generics give Java/C# a similar tool, they are very different. C++ templates actually create entirely different chunks of assembly code. C++ templates provide compile-time type-checking but they also provide run-time binaries. This makes C++ templates very fast and able to create extremely optimized code for each type used. This may surprise you, because you've heard from people with no C++ knowledge that templates are slow. People who say that are not familiar with templates in the least. On the other hand, generics simply provide compile-time type-checking. They do nothing more. So, as you can see, they are quite different from C++ templates.

Java One session (5, Informative)

LarsWestergren (9033) | more than 7 years ago | (#18754057)

Naftalin and Wadler are also holding a Java One session this year, it is on Wednesday, session id is TS-2890. If you have a Sun Developer Connection account (free) you can watch it online after the conference is over.

I agree with reviewer, the book is very good. It is true that Java generics is a compile time check, and that the generics information is removed (erasure). Nevertheless, that was a deliberate tradeoff for backwards compatibility, and it still makes coding complex Java a lot safer and easier. Look for instance at the 1.5 and 1.6 improvements to the concurrency libraries [sun.com] with Future, Callable and Executors.

Not a good way to teach (1)

Yurka (468420) | more than 7 years ago | (#18754283)

OK, this finally is a comment about the book itself, and not about its subject. In my practice, it is almost impossible to get people to understand that generics do not mean "a List of Objects now becomes a List of objects of certain type". Once a person latches onto this notion (that parameterization is simply a way of indicating something similar to a collection), he is almost impossible to shift from it - I've tried explaining the declaration of the base Enum (which is Enum<E extends Enum<E>> - to get the compareTo () to work in a type-safe manner) to seasoned Java developers, only to get (without exception, or even a Throwable): "Oh, I get it, that means that Enum contains other Enum-like things!". And yet the book dives right into this concept; the first glimpse of the actual meaning of parameterization does not appear until the section 2 of chapter 3, a good one third way through. If I were to do it the right way, I'd start with <T extends Comparable<T>>, explain it thoroughly, and only then allow Collection to enter the picture. So, I would disagree with the reviewer - if you want to understand ? super Foo, this is not the book, unless you are willing to skip the first 2 chapters.

C++ Templates (1)

fittekuk (1033554) | more than 7 years ago | (#18754295)

While Java generics may be simpler and easier to use than C++ templates, they fall far short of the feature set of C++ templates. They do not really provide "generic programming" in the same sense that C++ templates do. There is much more to generic programming than being able to have a HashMap.

In this case I'd take the tutorial over Wedler. (0)

Anonymous Coward | more than 7 years ago | (#18754381)

Which explains why Philip Wadler, one of the people responsible for Haskell, was part of a team that wrote GJ (Generic Java), one of the experimental Java mutations (others included PolyJ and Pizza) that, back in the day (late 90s) helped explore how parametric polymorphism could be added to Java, and which formed the basis for the generics introduced in Java 5.

So if you want to understand generics, Wadler is your man.


I think that this a very twisted and silly conclusion. Just because someone wrote or developed something doesn't automaticly imply that he or she is the best person when it comes to explaining everything about it. Quite frankly I think its much more of the opposite. Developers are by definition not the best people to turn to when you wish to really learn whatever they developed. While a developer would try to approach his ideas from a technical point of view most students would be more helped when you begin slow and abstract and eventually work your way up.

Naturally I'm a bit cynical here but heck. To me this has once again nothing to do with an intersting article but simply yet another post to try and push some "interesting" book forward thus hoping that someone is going to make more money out of it.

My opinion in all this is simple. If you're interested in Generics then the best place to start learning is the Sun Java tutorial [thejavatutorial.com] . In this case the trail about Generics [sun.com] would sound like a good idea to start reading.

And you know whats so good about this tutorial? Its free, its from the company which developed Java (a company which doesn't only have very good developers when it comes to Java but also has people available who are quite skilled on documenting) and you can even download it so that you can read and study even if you don't have a permanent connection to the Internet.
Load More Comments
Slashdot Login

Need an Account?

Forgot your password?