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.
在参数传递和返回值中使用autoBox
class AutoBox2 {
     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);
     }

}

你可能感兴趣的:(java,泛型,box,map,unbox)