我是JAVA的新手,目前正在学习Oracle教程泛型部分。我认为那里有一个错误,我想确保我没有记错。感谢您的反馈。
我在https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html看到了以下解释
Pair p =新的Pair <>(8,’a’); 请注意,Java编译器自动将8装箱为Integer.valueOf(8),将 ‘a’ 装箱 为Character(’a’) : Pair p =新Pair <>(Integer.valueOf(8), new Character(’a’) );
Pair p =新的Pair <>(8,’a’);
请注意,Java编译器自动将8装箱为Integer.valueOf(8),将 ‘a’ 装箱 为Character(’a’) :
Pair p =新Pair <>(Integer.valueOf(8), new Character(’a’) );
我认为这是一个错误,实际上将’a’自动装箱到 Character.valueOf(’a’) 。
我编写了以下程序进行检查。正如我认为泛型可能具有特殊的装箱方法,我尝试了泛型方法,常规方法和泛型类:
class TestCharacter<T>{ public <T> void check( T first, T second){ System.out.println("values: " + first + " " + second); System.out.println(first.equals(second)); System.out.println( "first == second is " + (first == second) ); System.out.println( "first == second is " + (first == Character.valueOf('a')) ); } } public class TestAutoBoxingIssue{ public static <T> void check1( T first, T second){ System.out.println("values: " + first + " " + second); System.out.println(first.equals(second)); System.out.println( "first == second is " + (first == second) ); System.out.println( "first == second is " + (first == Character.valueOf('a')) ); } public static void check2( Character first, Character second){ System.out.println("values: " + first + " " + second); System.out.println(first.equals(second)); System.out.println( "first == second is " + (first == second) ); System.out.println( "first == second is " + (first == Character.valueOf('a')) ); } public static void main(String[] args){ char first = 'a'; char second = 'a'; System.out.println("generic method usage: "); check1( first, second ); System.out.println("============="); System.out.println("regular method usage: "); check2( first, second ); System.out.println("============="); TestCharacter<Character> t = new TestCharacter<>(); System.out.println("generic class usage: "); t.check(first, second ); System.out.println("============="); }
}
输出为:
通用方法的用法:值:aa true first == second is true
常规方法的用法:值:aa true first == second is true
通用类用法:值:aa true第一==第二为true
因此,我认为这表明’a’被自动装箱到Character.valueOf。
我想念什么吗?这是检查的正确方法吗?
谢谢。
是的,valueOf在任何地方都可以进行自动装箱,以利用所有缓存。例如Character:
valueOf
Character
public static Character valueOf(char c) { if (c <= 127) { // must cache return CharacterCache.cache[(int)c]; } return new Character(c); }
这是文档监督。