ArrayExpand

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 数组变长算法! 数组对象长度不可改变,但是很多实际应用需要长度可变的数组,可以采用复制为容量更大的新数组, 替换原数组, 实现变长操作
 */
public class ArrayExpand {

	/**
	 * 计算一个字符在字符串中的所有位置
	 * 
	 * @param str
	 * @param key
	 * @return
	 */
	public static int[] count(String str, char key) {
		int[] count = {};
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c == key) {
				// 扩展数组
				count = Arrays.copyOf(count, count.length + 1);
				// 添加序号i
				count[count.length - 1] = i;
			}
		}
		return count;
	}

	public void testCount() {
		char key = '字';
		String str = "统计一个字符在字符串中的所有位置";
		int[] count = count(str, key);
		System.out.println(Arrays.toString(count));// [4, 7]
	}

	/**
	 * 动态给数组扩容
	 * 
	 * @param obj
	 *            需要扩容的数组
	 * @param addLength
	 *            给数组增加的长度
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object arrayGrow(Object obj, int addLength) {
		Class clazz = obj.getClass();
		if (!clazz.isArray()) {
			return null;
		}
		Class componentType = clazz.getComponentType();
		int length = Array.getLength(obj);
		int newLength = length + addLength;
		Object newArray = Array.newInstance(componentType, newLength);
		System.arraycopy(obj, 0, newArray, 0, length);
		return newArray;
	}

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// 数组变长(扩容)算法!
		int[] ary = { 1, 2, 3 };
		ary = Arrays.copyOf(ary, ary.length + 1);
		ary[ary.length - 1] = 4;
		System.out.println(Arrays.toString(ary));// [1, 2, 3, 4]
		// 字符串连接原理
		char[] chs = { '中', '国' };
		chs = Arrays.copyOf(chs, chs.length + 1);
		chs[chs.length - 1] = '北';
		chs = Arrays.copyOf(chs, chs.length + 1);
		chs[chs.length - 1] = '京';
		// 字符数组按照字符串打印
		System.out.println(chs);// 中国北京
		// 其他数组按照对象打印
		System.out.println(ary);// [I@4f1d0d
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值