JUST GO THRO' it:
In general, collections can hold Objects but not primitives. Prior to Java 5. a very common use for the wrapper classes was to provide a way to get a primitive into a collection. Prior to Java 5. you had to wrap a primitive by hand before you could put it into a collection. With Java 5, primitives still have to be wrapped, but autoboxing takes care of it for you.
here i m going to show this technique with three examples..........
Example1:
List mylnts = new ArrayList(); // pre Java 5 declaration
mylnts.add(new lnteger(42)); // had to wrap an int
in this example, we are still adding an Integer object to mylnts(not an int primitive) at autoboxing handles the wrapping for us.
As of Java 5 we can say
mylnts.add(42); //autoboxinghandles it!
Example2:
Integer var1=10; // pre Java 5 equivalent is int var1=10;
Integer var2=var1+15; // pre Java 5 equivalent is int var2=var1+15:
System.out.println(var2); //prints 25
Example3:
import java.util.*;
public class WordCounl {
public static void main(String[] args) {
Map m = new TreeMap();
for (String word : args) {
Integer wordCnt = m.get(word);
m.put(word. (wordCnt == null ? 1 : wordCnt + 1));
}
System.out.println(m);
}
}
What is really happening is this: In order to add 1 to wordCnt, it is automatically unboxed, resulting in an expression of type int Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map. it is automatically boxed into an Integer.
Thanks
A.T.J
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment