追加值动态地转换为长[]数组 [英] append values dynamically into an long[] array
问题描述
我需要一些关于增加值到一个数组的帮助
例如
长[] S =新长[] {0,1,2};
当我这样做我实例化数组中的值
但我如何追加到这上面的数组,如果我有另一个值
3,4,5
,使它像这样
S =新长[] {1,2,3,4,5,6};
我试过System.arraycopy功能,但我只能在此改变阵列,当我尝试添加到它,我得到一个空指针异常
感谢
解决方案:
我用这个有一个for循环接一个地放在值一旦
长[] TMP =新长[则为a.length + x.length]。
System.arraycopy(一,0,tmp中,0,则为a.length);
System.arraycopy(X,0,TMP,则为a.length,x.length);
A = TMP;
您不能追加元素在Java中的数组。阵列的长度在创造的点被确定,并且不能动态地改变。
如果你真的需要一个长[]
的解决方案是创建一个更大的阵列,复制过来的元素,并指出引用了新的阵列,像这样:
长[] S =新长[] {0,1,2};
长[] toAppend = {3,4,5};
长[] TMP =新长[s.length + toAppend.length]。
System.arraycopy(S,0,tmp中,0,s.length);
System.arraycopy(toAppend,0,TMP,s.length,toAppend.length);
S = TMP; //小号== {0,1,2,3,4,5}
然而,您可能想使用的ArrayList<龙>
为了这个目的在这种情况下,你可以使用附加元素。新增
- 方法。如果你选择了这个选项,就应该是这个样子
//初始化为0,1,2
ArrayList的<龙> S =新的ArrayList<龙>(Arrays.asList(0L,1L,2L));
//追加3,4,5
s.add(3L);
s.add(4L);
s.add(5L);
长[] longArray =新长[s.size()];
的for(int i = 0; I< s.size();我++)
longArray [I] = s.get(ⅰ);
i need some help regarding adding values into an array
for example
long[] s = new long[] {0, 1, 2};
when i do this i instantiate an array with the values
but how do i append to this to the above array if i have another value of
3, 4, 5
to make it like this
s = new long[] {1, 2, 3, 4, 5, 6};
i tried the System.arraycopy function but i am only able to overide the array and when i try to append to it, i get a null pointer exception
Thanks
SOLUTION
i used this with a for loop to put in the values once by one
long[] tmp = new long[a.length + x.length];
System.arraycopy(a, 0, tmp, 0, a.length);
System.arraycopy(x, 0, tmp, a.length, x.length);
a=tmp;
You can not "append" elements to an array in Java. The length of the array is determined at the point of creation and can't change dynamically.
If you really need a long[]
the solution is to create a larger array, copy over the elements, and point the reference to the new array, like this:
long[] s = new long[] {0, 1, 2};
long[] toAppend = { 3, 4, 5 };
long[] tmp = new long[s.length + toAppend.length];
System.arraycopy(s, 0, tmp, 0, s.length);
System.arraycopy(toAppend, 0, tmp, s.length, toAppend.length);
s = tmp; // s == { 0, 1, 2, 3, 4, 5 }
However, you probably want to use an ArrayList<Long>
for this purpose. In that case you can append elements using the .add
-method. If you choose this option, it should look something like
// Initialize with 0, 1, 2
ArrayList<Long> s = new ArrayList<Long>(Arrays.asList(0L, 1L, 2L));
// Append 3, 4, 5
s.add(3L);
s.add(4L);
s.add(5L);
long[] longArray = new long[s.size()];
for (int i = 0; i < s.size(); i++)
longArray[i] = s.get(i);
这篇关于追加值动态地转换为长[]数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!