Java array assignment (multiple values)

后端 未结 10 1458
醉梦人生
醉梦人生 2020-12-24 06:45

I have a Java array defined already e.g.

float[] values = new float[3];

I would like to do something like this further on in the code:

相关标签:
10条回答
  • 2020-12-24 07:27

    If you know the values at compile time you can do :

    float[] values = {0.1f, 0.2f, 0.3f};
    

    There is no way to do that if values are variables in runtime.

    0 讨论(0)
  • 2020-12-24 07:28
    int a[] = { 2, 6, 8, 5, 4, 3 }; 
    int b[] = { 2, 3, 4, 7 };
    

    if you take float number then you take float and it's your choice

    this is very good way to show array elements.

    0 讨论(0)
  • 2020-12-24 07:32

    This should work, but is slower and feels wrong: System.arraycopy(new float[]{...}, 0, values, 0, 3);

    0 讨论(0)
  • 2020-12-24 07:33

    On declaration you can do the following.

    float[] values = {0.1f, 0.2f, 0.3f};
    

    When the field is already defined, try this.

    values = new float[] {0.1f, 0.2f, 0.3f};
    

    Be aware that also the second version creates a new array. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

    0 讨论(0)
提交回复
热议问题