J2SE5.0 generis new features

xiaoxiao2021-03-05  24

The following procedures are easily understood, comparison of two programs, I believe it is easy to understand the GENERIS characteristics.

Oldlist.java

/ **

* @Author roson

*

*

2005-4-11

* /

Package collection;

Import java.util. *;

Public class oldlist {

Private void testlist ()

{

List list = new arraylist ();

List.add (New String ("HelloWorld!");

List.add (New String ("Goodbye!");

List.add (New Integer (95));

Printlist (list);

}

Private void PrintList (list list)

{

Iterator i = list.iterator ();

While (I.hasNext ())

{

String item = (string) i.next ();

System.out.println ("Item:" item);

}

}

Public static void main (String [] args) {

Oldlist old = new oldlist ();

Old.testlist ();

}

}

By compiling, it will be an error when executed to the third print.

Newlist.java

/ **

* @Author roson

*

*

2005-4-11

* /

Package collection;

Import java.util. *;

PUBLIC CLASS newlist {

Private void testnew ()

{

List list = new arraylist ();

List.add (New String ("HelloWorld!");

List.add (New String ("Goodbye!");

//list.add(new integer (95)); not adding shaping here

Printlist (list);

}

Private void PrintList (list list)

{

Iterator i = list.iterator ();

While (I.hasNext ())

{

String item = i.next ();

System.out.println ("Item:" item);

}

}

Public static void main (String [] args) {

NEWLIST LIST = New NewList ();

List.testnew ();

}

}

Here, if you join the comment, you will not be able to compile, not in the runtime. It is conducive to checking an error in advance.

Oldloop.java

/ **

* @Author roson

*

*

2005-4-11

* /

Package collection;

Import java.util. *;

Public class oldloop {

Public static void main (String [] args) {

List list = new arraylist ();

List.add (New String ("HelloWorld!");

List.add (New String ("Goodbye!");

Iterator i = list.iterator (); i.hasnext ();)

{

String item = (string) i.next (); system.out.println ("item:" item);

}

}

}

Newloop.java

/ **

* @Author roson

*

*

2005-4-11

* /

Package collection;

Import java.util. *;

Public class newloop {

Public static void main (String [] args) {

List list = new arraylist ();

List.add (New String ("HelloWorld!");

List.add (New String ("Goodbye!");

For (String str: list) / / more simple than before

{

System.out.println ("Item:" STR);

}

}

}

It can be easily seen from the above two programs, the second simple:)

discuss:

Here is only List as an example, of course, there are other, such as HashMaps, LinkLists, etc. Collection.

There are still many places in J2SE5.0, and there is not much to say here. However, you can refer to English document J2se5 nutshell and j2se5. I still feel that generis is not good at the beginning, but I feel that it is very convenient to see it in JBSS. It is really convenient. May wish to try!

转载请注明原文地址:https://www.9cbs.com/read-37173.html

New Post(0)