int与integer的使用

andayfour 2014-05-17 03:04:59
jdk1.5之后有l auto-boxing

String s="33";
int i=Integer.parseInt(s);

这样是可以正常run的
我看到现在项目里面的id都是Integer类型的
我想问,为什么不用int呢
用Integer好处在哪

String s="33";
int i=Integer.parseInt(s);

这段代码跑可以,但是有没有什么问题?
...全文
560 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
有些地方必须是对象 比Map<int,String> map;编译不行 ,而Map<Integer,String>可以 包装类 好处看api的方法
程大治 2014-05-17
  • 打赏
  • 举报
回复
int是形式变量,比如用一个void函数操作int,在原函数中值是不会变的,比如: public static void main(String[] args){ int i = 1; changeNum(i); System.out.println(i); //输出还是1 } public static void changeNum(){ i++; } 所以你已经发现,int只是基本数据类型,只能在生命周期内有效,他不是一个对象。 但是Integer作为一个对象存在,是实实在在的。 举个例子,你手里有一本书,别人撕掉一页,就少了一页。 但是你脑中有一本书,别人再怎么撕,因为他是不存在的,不是对象,别人只能操作对象,所以书还是原来的书。
fei_shui 2014-05-17
  • 打赏
  • 举报
回复
个人感觉 使用Integer更加符合面向对象开发
浊丶ge 2014-05-17
  • 打赏
  • 举报
回复
补充一下,integer和对象一样,存放在堆上,而基本数据类型存放在栈上。栈上的变量超过其作用域后,会释放内存,不能用在容器中。而对象是由java垃圾回收管理器来管理的。 对象有很多方法,方便使用。
haorengoodman 2014-05-17
  • 打赏
  • 举报
回复
Integer 的默认值是null int 的默认值 是 0 例如 一个人 的成绩, 如果用 int 来保存,没有赋值的 情况下 那 他的成绩 就是 0分 如果用 Integer 来保存, 没有赋值的情况 就是 null, 表示没有 没有 输入 成绩. 这样你该明白了吧.
A18767101172 2014-05-17
  • 打赏
  • 举报
回复
个人觉得Integer作为对象,有很多方法,可以进行很多方法的调用,而int作为基本数据类型,只能用作参数
ddddder 2014-05-17
  • 打赏
  • 举报
回复
int只是基本数据类型吧
日知己所无 2014-05-17
  • 打赏
  • 举报
回复

import java.util.*;

public class IntegerTest {

    public static void main(final String[] args) {
        Integer integer1 = new Integer("1");
        Integer integer2 = new Integer("1");
        if (integer1 == integer2) {
            System.out.println("Integer(\"1\") == Integer(\"1\")");
        } else {
            System.out.println("Integer(\"1\") != Integer(\"1\")");
        }

        Integer integer3 = 1;
        Integer integer4 = 1;
        if (integer3 == integer4) {
            System.out.println("1 == 1");
        } else {
            System.out.println("1 != 1");
        }

        Integer integer5 = 128;
        Integer integer6 = 128;
        if (integer5 == integer6) {
            System.out.println("128 == 128");
        } else {
            System.out.println("128 != 128");
        }

        // List<int> list = new ArrayList<>(); // 编译错误
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        for (Integer element : list) {
            System.out.println(element);
        }
    }
}
输出:(按下Ctrl+A查看) Integer("1") != Integer("1") 1 == 1 128 != 128 1 2 3 说明: 上面的示例的第30行使用基本数据类型int会发生错误,这应该是用Integer的最大的好处。 但是使用Integer也有很多需要注意的细节,请参考示例的输出。
q822846768 2014-05-17
  • 打赏
  • 举报
回复
楼上+1 Java 提供两种不同的类型:引用类型和原始类型(或内置类型)。 Int 是java 的原始数据类型,Integer 是java 为int 提供的封装类。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧