Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

java - append values dynamically into an long[] array

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...