gpt4 book ai didi

java - 是否有理由总是使用对象而不是基元?

转载 作者:搜寻专家 更新时间:2023-11-01 00:59:45 24 4
gpt4 key购买 nike

所以我刚刚开始了我的第二门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[])。我也明白有些情况需要使用对象。我的问题是:

一直使用该对象的可能原因是什么?特别是在这种简单的情况下,使用原语似乎更合适

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

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

谢谢

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

最佳答案

What possible reason is there for always using the object?

没有理由,这段代码很丑。作为对象的基元在使用集合时具有优势,但在您的示例中未使用它们。

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

绝对正确,这种情况下的对象更糟,它们需要更多内存并且在您的示例中没有优势。

Is it a bad habbit to always do this?

是的,您应该只在需要时使用对象(盒装基元)。除了在集合中使用,这样的对象也可以是null,这是一个优势,可以用作“值不(还)存在”等。

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

不,告诉他这没有意义。但请记住,您的教授从来不想上编程课。他可能是“被迫”这样做的。

Would this example I gave be considered bad programming?

是的。最大的坏!

关于java - 是否有理由总是使用对象而不是基元?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14284246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com