简体   繁体   English

创建具有可变数据类型的数组

[英]Creating an array with mutable data type

**Initializing an array of NaturalNumbers with values 1 through 4**

When I debug, I find the array = [5,5,5,5] and my goal is that the array = [1,2,3,4].当我调试时,我发现数组 = [5,5,5,5],我的目标是数组 = [1,2,3,4]。

        NaturalNumber[] array = new NaturalNumber[4];
        NaturalNumber count = new NaturalNumber2(1);
        for (int i = 0; i < array.length; i++) {
            array[i] = count;

            count.increment();

Here is a link to all the methods that can be used with natural numbers.这是可用于自然数的所有方法的链接。 I just do not understand how can I create the wanted array without changing count 's value.我只是不明白如何在不改变count值的情况下创建想要的数组。

http://web.cse.ohio-state.edu/software/common/doc/index.html?components/naturalnumber/NaturalNumber.html http://web.cse.ohio-state.edu/software/common/doc/index.html?components/naturalnumber/NaturalNumber.html

 NaturalNumber[] array = new NaturalNumber[4];
        NaturalNumber count = new NaturalNumber2(0);
        for (int i = 0; i < array.length; i++) {

            count = new NaturalNumber2(i);
            count.increment();
            array[i] = count;
**Initializing an array of NaturalNumbers with values 1 through 4**

你也可以这样做

int[] numbers = IntStream.range(1, 5).toArray();

You got 5,5,5,5 because you are using a boxed non-primitive type instead of a primitive.您得到 5,5,5,5 是因为您使用的是装箱的非原始类型而不是原始类型。

So references to NaturalNumber count are to the location of an object.因此对NaturalNumber count引用是指向对象的位置。 When you put that count into the array, you are putting the reference (four copies) and it contains the last value.当您将该count放入数组时,您将放入引用(四个副本)并且它包含最后一个值。 Since you do an increment as the very last thing in the last go-through the loop, it points to a value 5 (but is not the value 5).由于您在最后一次循环中作为最后一件事执行增量,因此它指向值 5(但不是值 5)。

If you declared int count instead and used count++ since you can't call .increment () on a primitive, then you'd get the sequence 1, 2, 3, 4. The run-time engine would put the actual value of count at each time into the array.如果您声明int count并使用count++因为您无法在原语上调用.increment () ,那么您将获得序列 1、2、3、4。运行时引擎将放置 count 的实际值在每次进入数组。

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

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