java改变数组长度_Java修改数组长度

java改变数组长度_Java修改数组长度java中没有关于修改数组长度的api,在此本人提供了修改数组长度的两个函数:arrayAddLength()和arrayReduceLength().详细见代码.[java]viewplaincopyprint?importjava.lang.reflect.Array;/***Description:Thisclassisusedtoadjustarraylength….

大家好,欢迎来到IT知识分享网。java改变数组长度_Java修改数组长度

java中没有关于修改数组长度的api,在此本人提供了修改数组长度的两个函数:arrayAddLength()和arrayReduceLength().详细见代码.

[java] view plaincopyprint?

import java.lang.reflect.Array;

/**

* Description: This class is used to adjust array length.

* @author e421083458

*

*/

public class ArrayTest {

/**

* @param args

*/

public static void main(String[] args) {

int a[]= new int[]{0,1,2,3,4,5};

int b[]= new int[]{0,1,2,3,4,5};

a = (int[]) arrayAddLength(a,2);

b = (int[]) arrayReduceLength(b,2);

//out print array lenght

System.out.println(a.length);

for (int i=0;i

System.out.print(a[i]);

}

System.out.println();

System.out.println(b.length);

for (int i=0;i

System.out.print(b[i]);

}

}

/**

* Description: Array add length

* @param oldArray

* @param addLength

* @return Object

*/

public static Object arrayAddLength(Object oldArray,int addLength) {

Class c = oldArray.getClass();

if(!c.isArray())return null;

Class componentType = c.getComponentType();

int length = Array.getLength(oldArray);

int newLength = length + addLength;

Object newArray = Array.newInstance(componentType,newLength);

System.arraycopy(oldArray,0,newArray,0,length);

return newArray;

}

/**

* Description: Array reduce lenght

* @param oldArray

* @param reduceLength

* @return Object

*/

public static Object arrayReduceLength(Object oldArray,int reduceLength) {

Class c = oldArray.getClass();

if(!c.isArray())return null;

Class componentType = c.getComponentType();

int length = Array.getLength(oldArray);

int newLength = length – reduceLength;

Object newArray = Array.newInstance(componentType,newLength);

System.arraycopy(oldArray,0,newArray,0,newLength);

return newArray;

}

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/15158.html

(0)
上一篇 2024-02-20 18:15
下一篇 2024-02-20 19:26

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信