J2SE1.5 Easy New Language Characteristics: Joshua Bloch Interview (3)

zhaozj2021-02-16  47

Can you combine generics and "for enhancement"?

No problem at all. You see, we integrate generic technology into the code above:

Void Cancelall (Collection C) {

For (Timertask Task: C)

Task.cancel ();

}

I think this is a more elegant code. Now the code can accurately indicate what he has to do and provides a guarantee of compile period type.

Please tell us Autoboxing.

Everyone knows that the Java language has two types of variables: one is the basic type, one is an object's indexing type (Object References). Basic types of variables cannot be placed in a collection, so if you want to put basic variables in a collection or remove it from the collection, you have to turn between basic types (such as int) and corresponding packaging classes (such as integer). turn to. Everyone who does this will feel that this is not a good practice.

For example, we consider a program that is used to count the frequency of the words in the command line. We use a map, its keyword is the word input, the value is the number of times the word appears in the command line:

PUBLIC CLASS FREQ {

Private static final integer one = new integer (1);

Public static void main (string args []) {

// Maps Word (String) to Frequency (Integer)

Map m = new trends ();

For (int i = 0; i

Integer Freq = (Integer) M.GET (Args [i]);

M.PUT (args [i], (freq == null? one:

New Inteder (freq.intvalue () 1))))))))

}

System.out.println (m);

}

}

How messy you see how the number of code is added in the loop? Now we use Autoboxing, generic and "For" to override this program:

PUBLIC CLASS FREQ {

Public static void main (string args []) {

Map m = new trememap ();

For (String Word: Args)

M.PUT (Word, M.Get (Word) 1);

System.out.println (m);

}

}

Is it much better? One thing worth notice: Program assumes that when you automatically remove null, you get 0. Is it a problem? Another alternative is to throw a NullPointRexception exception. These two options have their own advantages. "Automatically remove NULL gets 0" can beautify the above programs, but it may also cover real errors. If you have a strong opinion or a convincing solution about this problem, please contact the JSR-201 expert group.

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

New Post(0)