Handwritten array element copy

//数组拷贝
public class ArrayCopyDemo {
    
    
	public static void main(String[] args) {
    
    

		int[] src = {
    
     1, 2, 3, 4, 5, 6, 7 }; // 源数组

		int[] dest = new int[10]; // 目标数组
		System.out.println(Arrays.toString(src));
		System.out.println(Arrays.toString(dest));

		arraycopy(src, 1, dest, 4, 5); // 数组元素拷贝
		System.out.println(Arrays.toString(dest));
	}

	/**
	 * 
	 * @param src     源数组
	 * @param srcPos  从源数组的第srcPos位置开始拷贝
	 * @param dest    目标数组
	 * @param destPos 从源数组的第destPos位置开始插入
	 * @param length  拷贝元素长度
	 */
	private static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) {
    
    
		if (src == null || dest == null) {
    
    
			throw new NullPointerException("源数组和目标数组都不能为null");
		}
		if (!src.getClass().isArray() || !dest.getClass().isArray()) {
    
    
			throw new ArrayStoreException("源和目标必须都是数组");
		}
		if (srcPos < 0 || destPos < 0 || length < 0 || srcPos + length > Array.getLength(src)
				|| srcPos + length > Array.getLength(dest)) {
    
    
			throw new IndexOutOfBoundsException("数组索引越界");
		}
		if (src.getClass().getComponentType() != dest.getClass().getComponentType()) {
    
    
			throw new ArrayStoreException("源数组和目标数组类型必须相同");
		}
		// 待满足所有条件,开始拷贝
		for (int index = srcPos; index < srcPos + length; index++) {
    
    
			// 获取需要拷贝元素
			Object val = Array.get(src, index);
			// 给目标设置元素
			Array.set(dest, destPos, val);
			destPos++;
		}
	}
}

The results show that:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_40307206/article/details/102224962