zoukankan      html  css  js  c++  java
  • java例程练习(数组复制与arraycopy)

    //数组拷贝
    public class Test {
    	public static void main(String[] args) {
    		
    		String[] s = 
    		{"Microsoft", "IBM", "Sun", "Oracle", "Apple"};
    		
    		String[] sCopy  = new String[6];
    		
    		System.arraycopy(s, 0, sCopy, 0, s.length);
    		
    		for(int i = 0; i < s.length; i++) {
    			System.out.print(s[i] + " ");
    		}
    		System.out.println();
    		
    		for(int i = 0; i < sCopy.length; i++) {
    			System.out.print(sCopy[i] + " ");
    		}
    		System.out.println();
    			
    		
    		int [][] intArray = {{1, 2}, {1, 3, 4}, {4, 9}};
    		int [][] intArrayCopy = new int [3][];
    		System.arraycopy(intArray, 0, intArrayCopy, 0,intArray.length);
    		
    		
    		//有趣的问题从这里开始
    		intArrayCopy[2][1] = 100;
    		for(int i = 0; i < intArray.length; i++) {
    			for(int j = 0; j < intArray[i].length; j++) {
    				System.out.print(intArray[i][j] + " ");
    			}
    			
    			System.out.println();
    		}
    		
    		//浅层复制问题!
    	}
    }
    

    -----------------------------------------------------------------第二个版本,  对上面版本的一点点优化-----------------------------------------

    public class TestArrayCopy {
    	public static void main(String[] args) {
    		String[] s = { "Microsoft", "IBM", "Sun", "Oracle", "Apple" };
    
    		String[] sCopy = new String[6];
    
    		System.arraycopy(s, 0, sCopy, 0, s.length);
    
    		for (int i = 0; i < s.length; i++) {
    			System.out.print(s[i] + " ");
    		}
    
    		System.out.println();
    
    		for (int i = 0; i < sCopy.length; i++) {
    			System.out.print(sCopy[i] + " ");
    		}
    		System.out.println();
    
    		int[][] intArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7 } };
    		int[][] intArrayCopy = new int[3][];
    		System.arraycopy(intArray, 0, intArrayCopy, 0, intArray.length);
    		
    		/**
    		 * 用arraycopy会带来潜在的,浅层复制的问题!
    		 */
    		intArray[2][1] = 100;
    		
    		for(int i = 0; i < intArray.length;i++) {
    			for(int j = 0; j < intArray[i].length;j ++) {
    				System.out.print(intArray[i][j] + " ");
    			}
    			System.out.println();
    		}
    		System.out.println();
    		
    		for(int i = 0; i < intArrayCopy.length;i++) {
    			for(int j = 0; j < intArrayCopy[i].length;j ++) {
    				System.out.print(intArrayCopy[i][j] + " ");
    			}
    			System.out.println();
    		}
    	}
    }
    


  • 相关阅读:
    用Jquery控制文本框只能输入数字和字母
    Math:弧度制
    python学习之案例
    python自动化模块之实践一
    python学习之路 第六天
    python学习之路 第五天
    python学习之路 第四天
    python学习之路 第三天
    python学习之路 第二天
    python学习之路 第一天
  • 原文地址:https://www.cnblogs.com/wjchang/p/3671634.html
Copyright © 2011-2022 走看看