AutoBoxing

 
csdn回复的一个帖子。
当时看到这段代码感觉很荒谬。
1.Integer i1=100; //怎么可以这样初始化呢?
2.i1==i2          //2个不一样的对象比较怎么得出来得结果是true?
不过后来看到有人回复说是jdk1.5的新特性。
查了下jdk1.5的java language features
 
对于为什么Integer i1=100可以这样写有一点明白了
 
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
 
还附带了一个例子
  1. public class Frequency {   
  2.    public static void main(String[] args) {   
  3.       Map<String, Integer> m = new TreeMap<String, Integer>();   
  4.       for (String word : args) {   
  5.           Integer freq = m.get(word);   
  6.           m.put(word, (freq == null ? 1 : freq + 1));   
  7.       }   
  8.       System.out.println(m);   
  9.    }   
  10. }  

但可以对于为什么i1==i2打印出来时true还是想不明白。网上找资料。终于找到一篇比较靠谱的文章,提示说用dj反编译下看看。我试了下.
java 代码
  1. public static void main(String[] args) {   
  2.  Integer i=200;   
  3.  Integer ii=200;   
  4.  System.out.println(ii==i);   
  5.  Integer iii=100;   
  6.  Integer iiii=100;   
  7.  System.out.println(iii==iiii);   
  8.    Map<String, Integer> m = new TreeMap<String, Integer>();   
  9.    for (String word : args) {   
  10.        Integer freq = m.get(word);   
  11.        m.put(word, (freq == null ? 1 : freq + 1));   
  12.    }   
  13.    System.out.println(m);   
  14. }  
 
反编译为
 
public static void main(String args[])    {        Integer integer = Integer.valueOf(200);        Integer integer1 = Integer.valueOf(200);        System.out.println(integer1 == integer);        Integer integer2 = Integer.valueOf(100);        Integer integer3 = Integer.valueOf(100);        System.out.println(integer2 == integer3);        TreeMap treemap = new TreeMap();        String args1[] = args;        int i = args1.length;        for(int j = 0; j < i; j++)        {            String s = args1[j];            Integer integer4 = (Integer)treemap.get(s);            treemap.put(s, Integer.valueOf(integer4 != null ? integer4.intValue() + 1 : 1));        }        System.out.println(treemap);    }  
 
发觉原来和我想的不一样,我本来以为AutoBoxing是通过new一个wrapper class实现的结果却是用valueOf()。但是就算这样,那还是2个对象阿。
于是去看了下Integer.valueOf的源码。
 
public static Integer valueOf(int i) {        final int offset = 128;        if (i >= -128 && i <= 127) { // must cache         return IntegerCache.cache[i + offset];         }            return new Integer(i);     }  
 
说明对于一个byte范围大小的参数有特别的处理。于是看了下IntegerCache的源码
 
这是Integer的一个内部类
private static class IntegerCache {          private IntegerCache(){}          static final Integer cache[] = new Integer[-(-128) + 127 + 1];          static {             for(int i = 0; i < cache.length; i++)             cache[i] = new Integer(i - 128);          }    }   
 
现在我终于明白了
Integer i=200;    Integer ii=200;    System.out.println(ii==i);  
 
结果为true是因为它们就是同一个对象。IntegerCache初始化了256个Integer缓存。
i,ii只是一开始初始化的new Integer(100)的引用而已。
 
AutoBoxing终于明白了。
 
 
1. Bytecode is an intermediate code that is generated by a compiler to be executed by a virtual machine. It is platform-independent and can be executed on any platform that has a virtual machine installed. Machine code, on the other hand, is the binary code that is directly executed by a computer's CPU. Here are some examples of instructions in bytecode and machine code: - Bytecode (CIL): ldloc.0 (load local variable 0), ldc.i4.5 (load constant value 5), add (addition) - Machine code: mov eax, [ebp-4] (move value from memory to register), mov ebx, 5 (move constant value to register), add eax, ebx (addition) 2. Autoboxing and autounboxing is not needed in C# because C# has a feature called "value types" that allows the value types to be treated like objects. This means that value types can be used in collections and passed as parameters to methods without the need for autoboxing and autounboxing. 3. Auto-implemented properties should be used when there is no additional logic required for the getter or setter methods. If additional logic is required, then a regular property with custom getter or setter methods should be used. 4. Structs and classes are similar in that they both can contain fields, methods, and properties. The main difference is that structs are value types, while classes are reference types. This means that structs are passed by value, while classes are passed by reference. 5. A regular parameter declaration should be used when the method only needs to read the value of the parameter. A ref parameter declaration should be used when the method needs to modify the value of the parameter. 6. The "new" modifier is used to hide a method or property in a derived class, while the "override" modifier is used to replace a method or property in a base class with a new implementation in a derived class. 7. A two-dimensional array should be used when the data is logically a matrix or a table with rows and columns. An array of arrays should be used when the data is logically a collection of arrays. 8. In Java, the switch statement can cause errors if there are duplicate case values or if the break statement is not used after each case. In C#, the switch statement automatically eliminates these errors by requiring a default case and not allowing fall-through cases. 9. The foreach loop is used to iterate over a collection of items, such as an array or a list. Here is an example: ``` int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int number in numbers) { Console.WriteLine(number); } ``` 10. The program will print "True" and "False" because the delegate "f" contains two methods, "IsEven" and "IsSmallerThan3", which are both called when "f" is invoked with a parameter. The "+=" operator is used to add the "IsSmallerThan3" method to the delegate "f". A delegate is a type that encapsulates a method or a group of methods, and the "+=" operator is used to add a method to a delegate's invocation list.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值