append values dynamically into an long[] array

后端 未结 5 919
忘了有多久
忘了有多久 2020-12-20 20:44

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

相关标签:
5条回答
  • 2020-12-20 21:29

    appending isn't typically the kind of operation you'd do with arrays. I suggest you use ArrayList object, see API, which you can always convert back to an array.

    0 讨论(0)
  • 2020-12-20 21:29

    You have created an array of fixed size equals to three, you can't append more. You need to copy to a new array, with new size. See Arrays class

        long[] s = new long[] {0L, 1L, 2L};
        long[] l = Arrays.copyOf(s, 6);
        l[3] = 3L;
        l[4] = 4L;
        l[5] = 5L;
        System.out.println(Arrays.toString(l));
    

    The output is

    [0, 1, 2, 3, 4, 5]

    0 讨论(0)
  • 2020-12-20 21:38

    You cannot append values to array dynamically as the memory space is allocated to array object at the time of initializing, it means pre defined consecutive memory location is allocated.Hence we need to use array list because it uses linked list data structure internally and allows you to add/remove/sort easily without wasting any memory space.

    0 讨论(0)
  • 2020-12-20 21:39

    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);
    
    0 讨论(0)
  • 2020-12-20 21:39
    long[] s = new long[] {0, 1, 2};
    long[] s2=new long[]{3, 4, 5};
    int len_s= s.length;
    s= Arrays.copyOf(s, len_s+s2.length); //extends range arrays 
    System.arraycopy(s2,0,s1,len_s,s2.length); // copy three elements from s2 to s begin at s[len_s]; s2.length is number of elements s2.
    System.out.println(Arrays.toString(a1));
    

    output is

    [0,1,2,3,4,5]
    
    0 讨论(0)
提交回复
热议问题