System.arraycopy getting java.lang.ArrayIndexOutOfBoundsException

前端 未结 4 1666
再見小時候
再見小時候 2021-01-13 08:12

System.arraycopy getting ava.lang.ArrayIndexOutOfBoundsException.. I am trying to copy data from one array to the next. but I am getting a exception

privat         


        
相关标签:
4条回答
  • 2021-01-13 08:27

    array only has a length of 1 and you're trying to copy 8 things into it from array2. Try using an ArrayList or something that will grow as you need it to grow.

    0 讨论(0)
  • 2021-01-13 08:27

    SOLUTION TO ALL TYPES OF ARRAYINDEXOUTOFBOUNDS EXCEPTION:

    Understand this with the help of following example facing ArrayIndexOutOfBoundsException:

    public static void main(String [] args){
         String dest[] = { "Iphone", "Tutorials", "Gallery", "Android",    "item 1", "item 2", "item3", "item 4" };
            String src[]=new String[8];
            System.arraycopy(src, 0, dest, 1, src.length);
            System.out.println(dest[4]);
    }
    

    Solution to this above case can be any of the following: 1. Either increase the size of destination array so it could find a place. 2. Since we are starting from index 1 so you may copy only 7 elements from the source array. 3. Or you can start copying from index 0 in the destination array so it can accommodate all the array elements of source array.

    0 讨论(0)
  • 2021-01-13 08:45

    Because the length of array is 1.

    The declaration array[] = { "NO DATA YET" }; creates an array of length 1 with one item in it.

    Instead declare destination array as:

    private String array[] = new String[8];
    
    0 讨论(0)
  • 2021-01-13 08:46

    You're trying to copy 8 items into an array of length 1. You can't do that.

    From the documentation:

    Otherwise, if any of the following is true, an IndexOutOfBoundsException is thrown and the destination is not modified:

    • The srcPos argument is negative.
    • The destPos argument is negative.
    • The length argument is negative.
    • srcPos+length is greater than src.length, the length of the source array.
    • destPos+length is greater than dest.length, the length of the destination array.

    In this case, destPos + length is 8, and dest.length is 1, hence the exception is being thrown.

    Note that arrays in Java have a fixed length. If you want an expandable container, look at ArrayList.

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