原始数据类型和包装数据类型的用法有什么区别,包装数据类型的需求是什么? [英] What is the difference in usage of primitive and wrapper data type and what is the need of wrapper data type?
问题描述
我在网上到处搜索,但所有的答案都只是差异而已.我知道区别,但我不明白它们的应用程序的区别.
I searched it all over the web, but all the answers just consisted of the difference. I know the difference, but I don't understand the difference in their applications.
例如,假设我们必须取两个浮点值,如果我们使用double,我们可以很容易地使用a==b
进行比较,而如果我们使用Double,我们将不得不使用a.equals(b)
.
For example, suppose we have to take two floating values, if we use double, we can easily compare using a==b
, whereas if we use Double, we will have to use a.equals(b)
.
推荐答案
幕后还有更多.原因之一是 Collections API 是如何用 Java 开发的...
There is more than that behind the scenes. One of the reasons is how the Collections API is developed in Java...
考虑到你不能做这样的事情:
Consider that you just can not do anything like:
List<int> myList
在Java中.您将需要包装器
in Java. You will need the wrapper for that
List<Integer> myList
因为集合适用于对象而不是基元.
because the Collections work with objects and not primitives.
另一方面,包装器是为开发人员提供一组很好的方法/常量的对象,它们使某些操作更快更容易",例如:
On the other hand, wrappers are objects that offer the developers a nice group of methods/constants that make "faster and easier" some operations like:
int x = 17;
现在,感谢您可以使用包装器:
Now, thanks to the wrapper you can do:
String pars= Integer.toBinaryString(x);
pars= Integer.toHexString(x);
Integer.MAX_VALUE;
Integer.highestOneBit(x);
没有它,你会感到脖子疼,因为原始的 x
对你做这件事没有多大帮助.
Without that you will get a pain in the neck, since the primitive x
has not much helpful for you to do that.
这篇关于原始数据类型和包装数据类型的用法有什么区别,包装数据类型的需求是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!