How to resize array of integers in Java

3 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4};
       
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
       
        System.out.println();
       
        arr = Resize(arr, 6);
       
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
       
        System.out.println();
    }
    
    public static int[] Resize(int[] array, int newSize)
    {	
        int[] result = new int[newSize];
        int elements_to_copy = Math.min(array.length, newSize);

        System.arraycopy(array, 0, result, 0, elements_to_copy);

        return result;
    }
}
    
/*
run:
   
1 2 3 4 
1 2 3 4 0 0 
    
*/

 



answered Jun 28, 2017 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4};
       
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
       
        System.out.println();
       
        arr = Resize(arr, 3);
       
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
       
        System.out.println();
    }
    
    public static int[] Resize(int[] array, int newSize)
    {	
        int[] result = new int[newSize];
        int elements_to_copy = Math.min(array.length, newSize);

        System.arraycopy(array, 0, result, 0, elements_to_copy);

        return result;
    }
}
    
/*
run:
   
1 2 3 4 
1 2 3 
    
*/

 



answered Jun 28, 2017 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4};
       
        printArray(arr);
       
        arr = Resize(arr, 1);
       
        printArray(arr);
    }
    
    public static int[] Resize(int[] array, int newSize)
    {	
        int[] result = new int[newSize];
        int elements_to_copy = Math.min(array.length, newSize);

        System.arraycopy(array, 0, result, 0, elements_to_copy);

        return result;
    }
    public static void printArray(int[] array)
    {	
        for (int i = 0; i < array.length; i++)
		     System.out.print(array[i] + " " );
	    System.out.println();
	}
}
    
/*
run:
   
1 2 3 4 
1 
    
*/

 



answered Jun 28, 2017 by avibootz

Related questions

...