开发者

Object or primitive type

开发者 https://www.devze.com 2022-12-31 18:20 出处:网络
Can someone explain to me the usage of Integer, Boolean etc in place of their primitive types in JAVA?

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.

开发者_StackOverflow社区

Thanks!


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 );


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.


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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消