A Funny Java Flavoured Look at the World

Wednesday, April 19, 2006

Questions and Solutions using Generics, foreach and Enumerations

The link is to a free chapter from the Java Cookbook and is a chapter called - Data Structuring with Generics, foreach and Enumerations. The chapter is set out in an interesting way because it is split up into a number of questions and solutions and then discusses things to look out for.

8.1 Using Generic Collections
8.2 Using foreach Loops
8.3 Avoid Casting by Using Generics
8.4 Let Java Convert with AutoBoxing
and AutoUnboxing
8.5 Using Typesafe Enumerations
8.6 Program: MediaInvoicer

Each the sections above are split into three parts

problem
solution
discussion

so the chapter is a good introduction to problems but it also shows you how to actually use the new functionality rather than just know enough about the new Java 5 features to pass the SCJP 5 exam, which means it useful for people who aren't doing the exam as well.

For people who read this blog often you will know my fondness for free chapters, especially for topics that are going to appear on the Sun Certified Java Programmer Exam for JDK 1.5

The chapter talks about Generic collections, which is probably the main area Generics are going to be used because Generics are mainly added to bring in type safe collections and the ability to create collections which can only hold a certain object and will complain (throw an error) if you try to put in a different object.

It also talks about the Foreach/ for-each loop which is such an easy win. It is one of those pieces of functionality which you just wonder why it wasn't added before. It removes the need for iterators but allowing you to just loop though all the items in a collection. Anyway I will get off my high horse and stop ranting on about that.

Autoboxing is a bit wierd but in a good way. It allows you to use Java's wrapper classes (Integer etc) but with Java primitive variables which means you don't have to do needless casting. It does feel like a few of the features added into Java 5, a bit of a hack. This is so the code is backwarcompatiblele but it certainly does feel they have added it onto the code they already had, especially with the angled brackets and in particular the placing of the generic types.

here is the link, enjoy

http://www.oreilly.com/catalog/0596007019/chapter/ch08.pdf

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home