gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Imprinted Gifts
Career Education
Online Shopping
Remote Online Backup
GPS
KVM Switch over IP
Promotional Gifts
Online Education
Disney World Tickets
Shop Online
Cell Phones
Online Education
Baby Photo Contest
PDA Phones & Cases

 


Untitled table test
Register here for your free Internet.com membership to download your Justifying and Funding Infrastructure Investments report.

This independent report will help you make the case for your IT investments. Topics covered include:

Measuring Infrastructure Value
Justifying New Investments
Establishing an Infrastructure Value Chain and More.
Register now for your free Internet.com membership to download your complimentary Forrester report.
Limited Time Offer!
Developer News -
Sun Latest to Help App Vendors Get 'SasSy'    April 24, 2008
Ubuntu's 'Hardy' Cozy With Windows    April 24, 2008
The $4.6B Business of The Social    April 22, 2008
Office 2007 Fails The OOXML Test    April 22, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

J2SE 1.5 - Effective Java Programming with Tiger
By Arulazi Dhesiaseelan

Go to page: 1  2  Next  

Introduction

The forthcoming major release of Java 2 Platform, Standard Edition (J2SE) 1.5 is increasingly gaining its momentum in the developer community due to its potential improvements to the language and convincing feature set. The beta release of J2SE 1.5 is expected to ship in late 2003. J2SE 1.5, code named "Tiger," is being developed under the Java Community Process (JCP). The umbrella Java Specification Request (JSR) for this release is JSR 176. This article outlines the major features that are expected to ship with J2SE 1.5, which targets its FCS in the first half of calendar year 2004.

Component JSRs in Tiger

JSR 176 defines the release contents of Tiger. There are at least 15 component JSRs that are developed under the JCP program and targeted towards the Tiger release. Table 1 details the JSRs along with their status as of this writing.

Table 1: Tiger Component JSRs
JSR ID Description Current Status
003 Java Management Extensions (JMX) Specification Final Release 3
013 Decimal Arithmetic Enhancement Proposed Final Draft
014 Add Generic Types to the Java Programming Language Public Review
028 Java SASL Specification Maintenance Draft Review
114 JDBC Rowset Implementations Public Review 2
133 Java Memory Model and Thread Specification Revision Community Review
163 Java Platform Profiling Architecture Public Review
166 Concurrency Utilities Public Review
174 Monitoring and Management Specification for the Java Virtual Machine Public Review
175 A Metadata Facility for the Java Programming Language Community Review
199 Java Compiler API Expert Group Formation
200 Network Transfer Format for Java Archives Community Review
201 Extending the Java Programming Language with Enumerations, Autoboxing, Enhanced for Loops, and Static Import Community Review
204 Unicode Supplementary Character Support Community Review
206 Java API for XML Processing (JAXP) 1.3 Community Review

You can get the detailed information of these JSRs in the following URL: http://www.jcp.org/en/jsr/detail?id=JSR_NUMBER. Replace the JSR_NUMBER with the actual JSR ID in which you are interested. The status information mentioned in the above table is obtained from the individual JSR page in the JCP Web site.

Generics

What are generics?

Generics are also called parameterized types (often referred as type polymorphism). To make it more precise, Generics are similar to the powerful C++ templates, but remove the potential drawbacks faced by templates. Generics make type parameters explicit and type casts implicit; this is helpful in using libraries in a safer and flexible manner. One good example could be the collections library.

Generics support in Java is the language feature most frequently requested by the Java developers. This feature has been postponed for quite some time because it requires changes to the Java Language Specification, and also updates to the Java Virtual Machine (JVM) Specification. Finally, this feature stands as the top priority for the Tiger release.

Generics types

There are two forms of generics types:

  1. Parameterized types
  2. Type variables

A parameterized type consists of a class or interface type C and a parameter section <T1,. . .,Tn>. C must be the name of a parameterized class or interface, the types in the parameter list <T1,. . .,Tn> must match the number of declared parameters of C, and each actual parameter must be a subtype of the formal parameter's bound types.

A type variable is an unqualified identifier. Type variables are introduced by parameterized class and interface declarations and polymorphic method declarations [For simplicity, these definitions are borrowed from section 2.1 of "Adding Generics to the Java Programming Language: Participant Draft Specification dated April 27, 2001."]

The generics syntax allows developers to enforce parameters that extend a Class or implement an interface. This helps in restricting the type of parameters for a generic class/interface/method and they are referred to have bound types. Listing 2 details the usage of generics in parameterized types, classes, interfaces, and methods.

Parameterized Type Example

List<Integer> integerList       = new LinkedList<Integer>()
Map<String, Integer> integerMap = new HashMap<String, Integer>()
Stack<Integer> integerStack     = new Stack<Integer>()

Generic Class Example

public class C<T1, T2> {
  private T1 type1;
  private T2 type2;
  public C(T1 type1, T2 type2) {
    this.type1 = type1;
    this.type2 = type2;
  }
  public T1 getType1() {
    return this.type1;
  }
  public T2 getType2() {
    return this.type2;
  }

  public static void main(String args[]) {
    C<String, Integer> cStrInt = new C<String, Integer>("one", 1);
    String type1StrInt = cStrInt.getType1();
    Integer type2SI    = cStrInt.getType2();

    C<Integer, Boolean> cIntBool = new C<Integer, Boolean>(1, true);
    Integer type1IntStr = cIntBool.getType1();
    Boolean type2IntStr = cIntBool.getType2();
  }
}

Generic Interface Example

public interface I<T> {
  public T getConnectionPool();
  public void releaseConnectionPool(T connectionPool);
}

Generic Method Example

public class M {
  public static <T extends Comparable> T minimum(T a, T b) {
    if(a.compareTo(b) <= 0) return a;
      else return b;
  }
  public static void main(String[] args) {
    Integer b1  = new Integer(2);
    Integer b2  = new Integer(5);
    Integer min = minimum(b1, b2);
    System.out.println("Minimum of (2,5) : " + min);
  }
}

Listing 2: Generics usage in parameterized types, classes, interfaces and methods.

Generics Advantage

Listing 3 shows the usage of generics in collection libraries. When using generics, you need to define the type the collection can hold. This helps the collection maintain homogeneous objects. If an undefined type is added to this collection, you will be notified of errors at compile time. This helps us to identify the cause of the problem during the development time.

On the contrary, the traditional way of using heterogeneous objects in a collection may result in runtime errors. Sometimes, these errors, which are very crucial to the product's quality, are uncovered during deployment time.

With Generics

Map<Integer> map = new HashMap<Integer>();
map.put("one", new Integer(1));
Integer integer = map.values().iterator().next();

Without Generics

Map map = new HashMap();
map.put("one", new Integer(1));
Integer integer = (Integer)map.values().iterator().next();

Listing 3: Generics usage in a collection.

Thus, the generics approach is more readable and yet powerful than the traditional approach.

Collection Filtering

Filtering a collection is prone to ClassCastException when the collection elements are heterogeneous. This may fail at runtime due to invalid casts. This behaviour is overcome with the use of generics in collection filtering. This helps developers detect the errors at compile time.

Listing 4 shows the collection filtering today and filtering collection with generics.

import java.util.*;
public class CollectionFiltering {

  /*
   * Traditionally, collections are allowed to hold heterogeneous
       * elements. This causes run-time error due to poor type
       * checking. These errors are uncovered only during testing
       * or deployment time, which are very crucial to the success
       * of the product.
   */
  static void purgeFromCollection(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); ) {
      String s = (String) i.next();
      if(s.length() == 4)
        i.remove();
    }
  }
  /*
   * Generics restricts the collection to hold homogeneous
   * elements. When an element other than String is added to this
   * collection, this causes compile-time error. Generics helps us
   * in preventing the run-time exceptions.
   */
  static void purgeFromGenerics(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
      if(i.next().length() == 4)
        i.remove();
    }
  }
  public static void main(String args[]) {
      //switch between approaches for behaviour.
    //List<String> arrayList = new
                   ArrayList<String>();    //generics approach
    List arrayList = new ArrayList();      //traditional approach
    arrayList.add(new Integer(0));
    arrayList.add(new String("1"));
    arrayList.add(new String("2"));
    purgeFromCollection(arrayList);
  }
}

Listing 4: Collection filtering with generics.

Getting Started with Generics

Download the 2.2 early access release of the generics prototype from http://developer.java.sun.com/developer/earlyAccess/adding_generics/. This distribution contains a prototype implementation for JSR14 and JSR 201 language features. This release now requires JDK 1.4.2 bootstrap VM.

collect.jar contains stubs for generics collection classes for compiling against rt.jar.

gjc-rt.jar contains generic compiler as well as a number of modified platform classes. This file should be placed on your VM's bootstrap classpath when compiling and running code developed for use with this prototype.

Extract this distribution to a folder. Set the following environment variables for compiling and running generics code.

SET J2SE14=PATH_TO_J2SE1.4.x_INSTALL_DIR

For example in Windows 2000,

SET J2SE14=C:\j2sdk1.4.2

SET JSR14DISTR=PATH_TO_PROTOTYPE_DIR

For example, in Windows 2000,

SET JSR14DISTR=C:\adding_generics-2_2-ea

Use the scripts (javac.bat & java.bat) provided in the "%JSR14DISTR%\scripts" directory to compile and run the code used in this article.

Tools that Support Generics

Tools and IDEs are available for writing generics enabled code today. Some of them are listed below.

Clover 1.1.1
http://www.thecortex.net/clover/generics.html

DrJava
http://drjava.sourceforge.net/

IntelliJ IDEA 4.0
http://www.intellij.com/idea/features4

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Other Java Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Whitepaper: Embeddable Content Platform for OEM's
Best Practices for Developing a Web Site. Checklists, Tips & Strategies. Download Exclusive eBook Now.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES