我会告诉你我为什么用Integer.ValueOf()而不用new Integer()吗?
问题:当你需要产生一个整形的包装类的实例的时候(比如整数10),有两种方式:
第一种,使用构造函数new 一个对象:
Integer i=new Integer(10);
第二种,使用静态工厂方法产生实例(我会告诉你其实java里所有的ValueOf都是静态工厂方法吗?):
Integer i=Integer.ValueOf(10);
你选哪种?
我选第二种,为什么?因为,当你用第一种方式时每次都会产生一个新的实例,而当你使用静态工厂方法时,不一定会产生一个新的实例,注意我说的是不一定,至少这里没有产生一个新的实例,为什么,我们看源码:
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
这是Integer.ValueOf(int i)的源码,原来IntegerCache相当于做了一个缓存,在第一次被调用时,首先初始化生成了从-128到127共256个对象的数组,在以后凡是在这个范围内的int值都可以直接从此缓存中取,而不在再次生成Integer对象,大大提高了对象的利用率。
下面是IntegerCache的源码,这个就不解释了:
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
好了,很清楚了,之前我为什么说不一定不会new 一个新的对象,现在明白了,当你产生的数是-128到127时,不会new一个新的对象,超过这个范围时,同样是new 一个新的对象。
分享到:
相关推荐
这样的程序如果不在IDE 工具中输入,是很难看出这个程序代码会出现问题,可它偏偏就出问题了,这是为什么呢?因为程序里面有个静态方法,如果导入import static java.lang.Integer.parseInt;这样的程序就可以运行了...
licenseNum = nf.format(Integer.valueOf(licenseNum)); String verTime = new StringBuilder("-").append( new java.text.SimpleDateFormat("yyMMdd").format(cal.getTime())).append("0").toString(); String ...
Date enterDate = Date.valueOf(strDate); //util.Date SimpleDateFormat //判断两次密码是否相同 if(pwd == null || !pwd.equals(rePwd)){ request.setAttribute("error","两次密码必须相同"); request....
无论是用过的hibernate,mybatis,你都可以法相他们有一个共同点: 1. 从配置文件(通常是XML配置文件中)得到 sessionfactory. 2. 由sessionfactory 产生 session 3. 在session 中完成对数据的增删改查和事务提交等. 4....
所以我在讨论 C# 语言构造的时候会假设你知道 C++。 本文通过一系列例程以简短但全面的方式讨论了 C# 语言构造和特性,所以你仅需略览代码片刻,即可了解其概念。 注意:本文不是为 C# 宗师而写。有很多初学者的 ...
不要使用Response.Redirect,而应该使用Server.Transfer e.g // in global.asax protected void Application_Error(Object sender, EventArgs e) { if (Server.GetLastError() is HttpUnhandledException) Server...
codeceo 首页问答热门文章RSS订阅 文章首页 ...但是为什么呢?简单分析下。 看过上文的还记得在 HashMap 扩容的时候会调用 resize() 方法,就是这里的并发操作容易在一个桶上形成环形链表;这样当获取...
如果你有常用的定义好的,且测试通过的正规表达式,欢迎跟贴,也让我享用一下 . 类中用到了 jakarta-oro-2.0.jar 包,请大家自己在 apache网站下下载 在这是junit测试单元类我就不提交了,在main()方法中有几个小...
B) int i=Integer.MAX_VALUE; C) static int i=100; D) int 123_$; 3.以下的变量定义语句中,合法的是( )。 A) float $_*5= 3.4F; B) byte b1= 15678; C) double a =Double. MAX_VALUE; D) int _abc_ = 3721L; ...
不要使用Response.Redirect,而应该使用Server.Transfer e.g // in global.asax protected void Application_Error(Object sender, EventArgs e) { if (Server.GetLastError() is HttpUnhandledException) Server....
写一个函数,例如:给你的 a b c 则输出 abc acb bac bca cab cba import java.util.ArrayList; import java.util.List; public class NumTest { public static void main(String[] args) { String s="ABCD";...
redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取。 20、EJB与JAVA BEAN的区别? Java Bean 是可复用...
# PHP Fatal error: Uncaught TypeError: Return value of foo() must be of the type integer, float returned in test.php:6 在声明之后,就会触发致命错误。 是不是有点类似与 js 的 strict mode? 3. 标量...
redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取。 23、EJB与JAVA BEAN的区别? Java Bean 是可...
什么是SWFUpload? SWFUpload是一个客户端文件上传工具,最初由Vinterwebb.se开发,它通过整合Flash与JavaScript技术为WEB开发者提供了一个具有丰富功能继而超越传统标签的文件上传模式。 [编辑本段]SWFUpload的...
//定义输入的分数为“mark”,且分数会有小数 double mark; Scanner scanner = new Scanner(System.in); mark = scanner.nextDouble(); //判断是否有输入错误。 if(mark||mark>100){ System.out.println(...
sql> tablespace_name [pctfree integer] [initrans integer] [maxtrans integer] sql> [logging | nologging] [nosort] storage(initial 200k next 200k pctincrease 0 sql> maxextents 50); <3>.pctfree...