Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: How to resize an array

 int,string,char,static, url, socket, url, socket, java
{filelink=23}

/**
 * @(#)UpdateArraySize.java
 *
 *
 * @author Sakoba
 * @version 1.00 2012/12/1
 */
 
import java.util.*;
import java.lang.reflect.Array;
 
public class UpdateArraySize {
 
    public static void main (String[] args) 
    	{
    		String array[]={"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    		// Print original size
    		System.out.printf("original size=>%s\nContent=>%s\n",
    		  array.length, Arrays.toString(array));
    		 // resize the array
    		 array=(String[])resizeArray(array, 2);
    	    System.out.printf("After changing size=>%s\nContent=>%s",
    		  array.length, Arrays.toString(array));
        }
 
      public static Object resizeArray(Object a, int newLength) 
    {
    	Class cl = a.getClass();
    		if (!cl.isArray()) return null;
    	int length = Array.getLength(a);
        Class componentType = a.getClass().getComponentType();
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a, 0, newArray, 0, newLength);
        return newArray;
    }
}
/*
original size=>5
Content=>[Monday, Tuesday, Wednesday, Thursday, Friday]
After changing size=>2
Content=>[Monday, Tuesday]
*/

Users who found this page were searching for:

  • java array resize
  • write a program to find the factorial of the given number in perl
  • java array resize
  • java JButton examples JDK7
  • calendar in jpanel
  • tkinter input output
  • java %tt
  • java resize array
  • to find the factorial in perl
  • how to redirect stack trace

No comments yet.

Leave a Comment