4

所以我刚开始我的第二门Java编程课,这是教授给我们的例子,用来演示循环和数组。

public class ArraysLoopsModulus {                       
public static void main(String [ ] commandlineArguments){                   
  //Declare  & Instatiate an Array of 10 integers
  Integer[ ] arrayOf10Integers = new Integer[10];

  //initialize the array to the powers of 2
  Integer powersOf2 = new Integer(1);   
  for(int i=0;i<arrayOf10Integers.length;i++){
    arrayOf10Integers[i] = powersOf2;
    //multiply again by 2
    powersOf2 = powersOf2 * 2;
  }

  //display the powers of 2     
  System.out.println("The first 10 powers of 2 are: ");
  for(int i=0;i<arrayOf10Integers.length;i++){
    System.out.print(arrayOf10Integers[i] + ", ");
  }  
}
}

浏览了所有即将出现的示例后,我的教授似乎从不使用原始数据类型,他总是使用等效的对象类(在这种情况下,Integer代替intInteger[]代替int[])。此外,我了解某些情况需要使用对象。我的问题是:

总是使用该对象有什么可能的原因?尤其是在这种简单的情况下,使用原语似乎更合适

总是这样做是一个坏习惯吗?我是否应该总是使用对象只是为了让他开心,但在现实生活中知道尽可能使用原始数据类型

我给出的这个例子会被认为是糟糕的编程吗?

谢谢

编辑: 感谢所有出色的答案,我(一个初学者)只需要确认我在这里看到的不是最好的编码方式。

4

9 回答 9

12

What possible reason is there for always using the object?

There is no reason, this code is ugly. Primitives as objects have advantage when using collections, but they are not used in your example.

Especially in this simple case when the use of the primitive seems to fit better

Absolutley correct, Objects in this case are worse, they need more memory and have no advantage in your example.

Is it a bad habbit to always do this?

Yes, you should only use Objects (boxed primitives) if they are needed. Beside use in collections, such object can also be null, this is an advantage which can be used as "value not (yet) existing", etc.

Should I always use the objects just to make him happy, but know in real life to use the primitive data types when possible

No, tell him that this makes no sense. But keep in mind, that your professor never wanted to give progarmming lessons. He was probably "forced" to do so.

Would this example I gave be considered bad programming?

Yes. maximum bad!

于 2013-01-11T18:23:50.393 回答
9

From Effective Java by Joshua Bloch,

Item 49: Prefer primitive types to boxed primitives. There are three main differences between primitive types and boxed primitives:

  • Primitives have only their values, whereas boxed primitives have identities distinct form their values.

  • Primitive types cannot be null, but boxed primitives can.

  • Primitive types are more space and time efficient than boxed-primitives.

Care must be taken with using the == operator with boxed primitives as, with any other reference type, it compares identity and you almost certainly want to be comparing value. If a boxed primitive is compared to a primitive with the == operator, the primitive type is boxed and the identities compared, so care must also be taken here.

The process of boxing and unboxing, especially in a loop can serious impede performance.

Basically, boxes primitives should be avoided unless primitive types cannot be used, such as in collections or as parameterised types.

I hope this helps you understand the difference.

于 2013-01-11T18:26:52.193 回答
4

Most people agree you should use primitives when you can. To play the devil's advocate, I thought of one advantage: They fail faster.

This code will throw a null pointer exception because you forgot to initialize myInteger:

private Integer myInteger;

public void run () {
    int myNewInt = myInteger + 5;
}

If you used an int, it'd proceed and it'd be harder to notice the mistake you made.


Here's another similar advantage I just ran into: It lets you represent the absence of data. I have a method that returns a configuration option. It has a signature that returns a boolean. Turns out the configuration option didn't exist in the system. But instead of telling me that, it just defaults to false (it has to pick something). As a result, I thought this value was set to false but turned out it was missing. The bug would have been more obvious if the method returned a Boolean.

于 2013-01-11T18:38:38.367 回答
1

例如,原语不能存储在Collectins.

好的自动装箱有帮助,但帽子只是由编译器而不是你自己的。

于 2013-01-11T18:18:09.870 回答
1

不,您不应该在任何地方使用原始类型的对象包装器:

1) 对象等价物使用比原始类型更多的内存。

2)这可能是两个Integer对象的无效比较的原因-您应该使用equals方法比较它们-不方便。

The only sensible reason for using Object wrappers is generics where you have to use some Class. For example such collections as List<Integer> or Map<Integer, Double>.

Another reason is if you have to store null value of variable instead of any numeric.

Provided block of code has a lot of redundant pieces.

于 2013-01-11T18:22:56.403 回答
1

Primitives are more space efficient, as the object wrappers create a new Object just to hold the same primitive you'd normally work with. Java has a lot of optimizations these days that make your professor's code not totally slow/broken, but it's certainly a bad practice.

In general, you should use primitives wherever you need them, unless you discover that you need object support, notably like @MrSmith42 suggests, if you want to store primitives in a Java Collection, like an ArrayList.

There's rarely any good reason to create an array of wrapper objects. Primitive arrays are very space efficient, arrays of objects lose all of that efficiency.

于 2013-01-11T18:23:21.767 回答
1

Contrary to popular opinion here, I am with your professor on this one. I prefer using the primitive wrapper objects much of the time. I think it comes down to programming style.

Example: I have a method that calls up the database to get an int. The method returns an Integer object. If the int doesn't exist it can return a null object. If it returns a non-null object then I know that the item exists in the database and is a valid number.

With a primitive you have to return a number, or throw an exception, but sometimes neither of these is appropriate.

So I do think there are plenty of valid reasons for using the wrapper-type objects. Most people's reasons for not using them is that they don't perform as well. This is often premature optimisation and in a real-life code base writing simple, robust code is usually far more important (depending on the application).

于 2019-07-26T10:44:13.693 回答
0
powersOf2 = powersOf2 * 2;

How about shifting bytes?!

//convert to primitive than someting like :

powersOf2  = powersOf2 << 2; 
于 2013-01-11T18:30:20.147 回答
0

According to Java documentation on The Number Classes tutorial it specifies only three reasons that you MIGHT want to use a Number object rather than a primitive. I would assume that any other reasons that not listed below will then be considered bad programming.

  1. As an argument of a method that expects an object (often used when manipulating collections of numbers).
  2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
  3. To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).
于 2016-06-19T00:14:03.087 回答