我用泛型类型写了一个简单的程序.但是,这个简单的示例在不同的JDK版本上表现不同.
简单的代码如下:
import java.util.List;
public class GenericTypes {
public static String method(List<String> list) {
System.out.println("Method method(List<String> list) is invoked.");
return "";
}
public static int method(List<Integer> list) {
System.out.println("Method method(List<Integer> list) is invoked.");
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
场景#1 ==>在JDK 1.7上,出现编译错误
`Method method(List<String>) has the same erasure method(List<E>) as another method in type GenericTypes.`
Run Code Online (Sandbox Code Playgroud)
方案#2 ==>在JDK 1.6或1.5上,没有编译错误.
控制台中代码和输出的屏幕截图如下:
众所周知,自JDK 1.5以来就引入了Generic Type.但是,通过上面的简单示例,它在不同的JDK版本中表现不同.
这是我的问题:
Q1 ==> 在更高的JDK版本(如JDK 1.7)中,在某些情况下,如上述简单示例,使通用类型行为有所不同?
Q2 ==> 上面的例子中编译错误是否比没有编译错误好?
这个你能帮我吗.非常感谢你提前.
我发现在JDK 1.6或更高版本的HashMap类中,与之前的JDK版本(如1.5)相比,一些代码被更改为null.
在JDK1.5中,定义了一个名为NULL_KEY的静态最终Object :static final Object NULL_KEY = new Object();
方法,其中包括maskNull
,unmaskNull
,get
和put
等,将使用该对象.
看到
static final Object NULL_KEY = new Object();
static <T> T maskNull(T key) {
return key == null ? (T)NULL_KEY : key;
}
static <T> T unmaskNull(T key) {
return (key == NULL_KEY ? null : key);
}
public V get(Object key) {
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length); …
Run Code Online (Sandbox Code Playgroud) 我发现缓存机制在jdk 1.6或更高版本的jdk中有所改进.
在jdk 1.5中,Integer中的缓存数组是固定的,请参阅
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
Run Code Online (Sandbox Code Playgroud)
在jdk 1.6或更高版本中,名为的方法getAndRemoveCacheProperties
和IntegerCache.high
属性已添加到Integer类中,
喜欢,
// java.lang.Integer.IntegerCache.high属性的值(在VM init期间获得)
private static String integerCacheHighPropValue;
static void getAndRemoveCacheProperties() {
if (!sun.misc.VM.isBooted()) {
Properties props = System.getProperties();
integerCacheHighPropValue =
(String)props.remove("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null)
System.setProperties(props); // remove from system props
}
}
Run Code Online (Sandbox Code Playgroud)
通过此更改,可以为缓存配置最高值并使用新的缓存范围.(-128 <= cachedValue <= highestValue
).
*以下是我的问题:*
Q#1为什么缓存范围在jdk 1.5中使用[-128~127]或jdk 1.6或更高版本的默认缓存?它只是支持bytes
和char '\u0000'~ 'u007f'
?
Q#2在jdk 1.6或更高版本中为缓存范围指定高值有什么好处?什么样的appilication或sceen适合我们这样做? …
我正在尝试使用以下两种方式创建数组:
方式#1-->
// 1-D String Array
String[] strs1 = new String[8];
// 2-D String Array
String[][] array1 = new String[8][8];
Run Code Online (Sandbox Code Playgroud)
方式#2-->
// 1-D String Array
String[] strs1 = (String[]) Array.newInstance(String.class, 8);
// 2-D String Array
String[][] array2 = (String[][]) Array.newInstance(String.class, 8, 8);
Run Code Online (Sandbox Code Playgroud)
以上两种创建数组的方式有什么区别?*哪个更好?* 请帮我解决这个问题。提前致谢!