简体   繁体   English

在Java中将变量直接分配给包装器类是一种好习惯吗?

[英]Is assigning variables directly to a wrapper class a good practice in Java?

As I am slowly progressing through the java tutorials, I came across java helper classes. 在逐步学习Java教程的过程中,我遇到了Java帮助程序类。 The code is 该代码是

public static void main(String args[]) {
char myLittleChar = 'b';
char myBigChar = Character.toUpperCase(myLittleChar);
System.out.println(myBigChar);

However, it worked the same even when assigning directly to a helper class. 但是,即使直接分配给助手类,它的工作原理也一样。

Character c = 'a';
System.out.println(c.toUpperCase(c));

and the same applied for short or float as well. 同样适用于short或float。

However, I didn't come across this much in any tutorial, or any sample code, and is declared as int , short etc. Is it considered a bad practice? 但是,我在任何教程或任何示例代码中都没有遇到太多,而是声明为intshort等。这是否被认为是不好的做法? If so, why? 如果是这样,为什么?

Thank you. 谢谢。

Character wraps the primitive two-byte char in an object. 字符将原始的两个字节的char包装在一个对象中。 That is superfluous. 那是多余的。 You could write 你可以写

char myBigChar = Character.toUpperCase('b');

So it is a matter of efficiency. 因此,这是效率问题。

By the way String already is an object, and does not have this verbosity. 顺便说一下,String已经是一个对象,并且没有这种冗长的含义。

If I understand what you're asking, you want to know the utility ot wrapper Object classes versus their primitive counterparts. 如果我了解您的要求,那么您想了解实用的ot包装器Object类和原始类。

There are many advantages to wrapper classes: 包装器类有很多优点:

  • They can be used as generic types 它们可以用作泛型类型
  • They are nullable 它们可以为空
  • They provide utility methods on their wrapped primitive value and other static methods 他们提供了包装后的原始值的实用方法和其他静态方法
  • etc. 等等

On the other side of your question, there's a concept called boxing / unboxing. 在问题的另一面,有一个叫做装箱/拆箱的概念。

When you: Character c = 'a'; 当您: Character c = 'a'; , you are autoboxing primitive value 'a' into its wrapper Character class. ,您正在将原始值'a' 自动装箱到其包装的Character类中。

If you follow that assignment with something like: char a = c; 如果按照以下方式进行分配: char a = c; , you are automatically unboxing the wrapper's value into its primitive counterpart. ,则会自动将包装器的值拆箱到其原始副本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM