public static Character valueOf(char c) {
if(c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
catche是这样的
static final Character cache[] = new Character[127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache = new Character((char)i);
}
文档的解释是下面的!既然传递进来了一个 c 那么 他的数值范围肯定是<127的了,源码中的return new Character(c)还会执行吗?java允许废话吗?
catche是static final的也就是说内存中肯定存在了各个char对应的Character 啊?
/**
* Returns a <tt>Character</tt> instance representing the specified
* <tt>char</tt> value.
* If a new <tt>Character</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Character(char)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param c a char value.
* @return a <tt>Character</tt> instance representing <tt>c</tt>.
* @since 1.5
*/
另外看了下Integer的也是这样写的,Float也一样,也是说缓存机制,但是Float的方法确没有这么实现,而是直接用的return 实例。
public static Integer valueOf(int i) {//源码有cache
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
public static Float valueOf(float f) {//不是说缓存吗?哪呢?
return new Float(f);
}