java box unboxing
生活随笔
收集整理的這篇文章主要介紹了
java box unboxing
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
| http://www.java2s.com/Tutorial/Java/0040__Data-Type/BoxingandUnboxing.htm Boxing and Unboxing |
| 1、Boxing refers to the conversion of a primitive to a corresponding wrapper instance, such as from an int to a java.lang.Integer. 2、Unboxing is the conversion of a wrapper instance to a primitive type, such as from Byte to byte. |
????static int m(Integer v) {
????????return v; // auto-unbox to int
????}
????public static void main(String args[]) {
????????Integer iOb = m(100);
????????System.out.println(iOb);
????}
} 下面程序注意點: 1、map的get? ,put方法 2、auto-unboxing import java.util.*;
public class TestArgsWords{
???? private static final int one =1;
????????
???? public static void main(String args[]){
????????
????Map m = new HashMap();
????for(int i=0;i<args.length;i++){
????
??????Integer freq= (Integer)m.get(args[i]); ???? ?//map的get方法返回值是object,所以首先將object類型轉換為Integer,然后傳給freq
??????m.put(args[i],(freq==null? one:(freq+1)));?//freq自動解包成int值
????}
????System.out.println(m.size() + "distinct word detected");
????
????System.out.println(m);
???? }
} 執行結果:
#java TestArgsWords aa????aa????bb cc ab????bb
#4distinct word detected
{aa=2, ab=1, bb=2, cc=1} 3、利用泛型Generic改良上述程序 import java.util.*;
public class TestArgsWords{
???? private static final int one =1;
????????
???? public static void main(String args[]){
????????
????Map<String,Integer> m = new HashMap<String,Integer> (); //map?泛型
????for(int i=0;i<args.length;i++){
????
??????Integer freq= m.get(args[i]); //減少 m.get(args[i])的強制類型轉換
??????m.put(args[i],(freq==null? one:(freq+1)));
????}
????System.out.println(m.size() + "distinct word detected");
????
????System.out.println(m);
???? }
}
轉載于:https://blog.51cto.com/vicky001/403771
總結
以上是生活随笔為你收集整理的java box unboxing的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 领域驱动设计的简略设计步骤
- 下一篇: 桌面虚拟化之用户行为审计