jeffreyhy

星期二 五月 08, 2007

new features in java5 and java6 -----1

As you know, there are many changes from java 1.4.2 to java 5 and relatively fewer changes from java 5 to java 6. So, I'll put the new features of java 5 and java 6 together.

Generic

the problem:
Vector v = new Vector();
v.add(new Integer(4));
OtherClass.expurgate(v);
... static void expurgate(Collection c) {
for (Iterator it = c.iterator(); it.hasNext();)
/* ClassCastException */
if (((String)it.next()).length() == 4)
it.remove();
}

Problem:

Collection element types
Compiler is unable to verify types
Assignment must use the cast operator
This can generate runtime errors
(ClassCastException)

Solution:

Tell the compiler what type the collection is
Let the compiler fill in the cast
Guaranteed to succeed

Instantiate a generic class to create type specific object

Vector x = new Vector();
x.add(new Integer(5)); // Compiler error!

评论:

发表一条评论:
  • HTML语法: 禁用

Calendar

Feeds

Search

Links

Navigation

Referrers