【问题标题】:Difference of int to int[]int 与 int[] 的区别
【发布时间】:2014-09-30 00:06:09
【问题描述】:

intint[] 有什么区别。是否允许将int 转换为int[]

例如:

int[] a = {};
int b;

如何将 b 的值传递给 a?

【问题讨论】:

  • 苹果和用于存放苹果的板条箱(可能是空的,也可能不是空的)之间的区别是一样的。

标签: java arrays int


【解决方案1】:

你不能,那是一个空数组,并且数组有固定的大小(它们在创建时接收它们的大小)。

一种可能的方法是:

int b = 6;
int[] a = {b};

但这等于:

int[] a = new int[1];
int b = 6;
a[0] = b;

这并没有什么意义,因为它只存储一个元素,所以你可能想要使用集合,因为它们是可变长度的——比如List

List<Integer> a = new ArrayList<Integer>();
int b = 6;
a.add(b);

至于您最初的问题,int 存储一个整数(非十进制),而int[] 存储一个固定数量的ints。

【讨论】:

  • 在您的答案中添加集合可能会使 OP 感到困惑,因为您必须引入 Integer 对象而不是原语。
  • @JamesB 感觉就像他试图创建一个空列表然后像使用脚本语言一样附加到它,因此我添加了集合。
  • 我知道你来自哪里。只是说你可能会用比 OP 要求的更多信息来超载你的答案。
【解决方案2】:

int []int 类型的数字数组,只接受 int 类型而不是其他类型

你可以看到一个类似的数组,它只接受类型 int

  1. when you define the length, you cannot change it after that
  2. when you define the type, it will just accept that type not anything else
  3. There are boundaries as you see in the picture so you can go beyond boundaries.

int 是原始类型,你可以看到它像

如何将int传递给int[],可以

代码:

    int a =9;
    int[] b = {a};

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2021-12-22
    • 2014-10-29
    • 2015-07-23
    • 2011-11-24
    • 2010-12-08
    • 1970-01-01
    • 2017-02-23
    • 2021-11-21
    相关资源
    最近更新 更多