加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 是否有理由始终使用Objects而不是原语?

发布时间:2020-12-15 02:04:52 所属栏目:Java 来源:网络整理
导读:所以我刚开始用 Java编写第二个编程类,这是教授给我们演示循环和数组的例子. public class ArraysLoopsModulus { public static void main(String [ ] commandlineArguments){ //Declare Instatiate an Array of 10 integers Integer[ ] arrayOf10Integers =
所以我刚开始用 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而不是int和Integer []而不是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?

是.最大的坏!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读