Object or primitive type

霸气de小男生 提交于 2019-12-12 10:49:58

问题


Can someone explain to me the usage of Integer, Boolean etc in place of their primitive types in JAVA?

I can't seem to grasp the advantages their are providing. They seem to create unnecessary problems of handling null values.

Thanks!


回答1:


Boolean, Integer, Long, ... are Objects. You can use them in places where you can't use primitive types, e.g.

  • storing them in a Collection like a Map
  • using them as template parameter
  • assigning them a null value
  • using them in a more general way (e.g. Long as Number)

Examples:

new ArrayList<Integer>();
Long id = null;
Number num = new Long( 3 );



回答2:


The rationale for Integer, Boolean, and so on is to allow primitive types to be used in contexts that require a reference type. The classic use-case is the collection APIs which provide sets, lists, maps, queues and so on where the element type must be some reference type.

Thus I can write:

List<Integer> list = new ArrayList<Integer>();

but the following is a compilation error:

List<int> list = new ArrayList<int>();

Note that this use-case for the primitive wrapper types predates both generic types and the "new" collections APIs, and goes back to the days where the only collection types were the original (pre-generic) forms of Vector and Hashtable, and their ilk.




回答3:


Sometimes you really need a value to be nullable, for instance if your app stores user data, a social security # may be unknown. In that case it's cleaner to store null instead of -1.

Also there are things you can't do with primitive types, like storing them in a map or using polymorphism (Double and Integer both are instances of Number).




回答4:


primitives are always faster.
however there are times, when objects are really useful:
1. upcasting. Your function can take Number(is a parent for all numeric objects: Integer, Float, etc.) for an argument.
2. Possible null value. For example it is used while storing in database. Object can be null, primitives must have value. So if field in db is nullable, it is better to use object version of primitive value.
3. if function takes object and you always give it a primitive there are expenses on autoboxing(turning primitive into object). The same for returning from function.
4. Objects have certain methods, such as getHashcode(), toString() etc., which can be really useful in some cases.



来源:https://stackoverflow.com/questions/2879916/object-or-primitive-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!