clonedemo.java

来自「Java学习源代码检索系统免费版」· Java 代码 · 共 73 行

JAVA
73
字号
//==============================================================
// CloneDemo.java - Implementing the Cloneable interface
//
// Java学习源代码检索系统 Ver 1.0 20031015 免费正式版
// 版权所有: 中国IT认证实验室(www.ChinaITLab.com)
// 程序制作: ChinaITLab网校教研中心
// 主页地址: www.ChinaITLab.com    中国IT认证实验室
// 论坛地址: bbs.chinaitlab.com  
// 电子邮件: Java@ChinaITLab.com
//==============================================================

// A simple string container class
class IntContainer implements Cloneable {
 private int size;  // Size (capacity) of array
 private int intArray[];
 public IntContainer(int n) {
  intArray = new int[n];
  size = n;
 }
 public int getValue(int n) { 
  return intArray[n]; 
 }
 public void putValue(int index, int value) { 
  intArray[index] = value;
 }
 public int size() {
  return size;
 }
/*
// The WRONG way to clone
 public Object clone() throws CloneNotSupportedException {
  return super.clone();  // ???
 }
*/
// The RIGHT way to clone
 public Object clone() throws CloneNotSupportedException {
  IntContainer temp = (IntContainer)super.clone();
  temp.intArray = (int[])intArray.clone();
  return temp;
 }
}   

// Main program class
class CloneDemo {

 // Display values in two containers side-by-side
 public static void showContainers(String msg, 
  IntContainer c1, IntContainer c2) {
  System.out.println("\n" + msg);
  for (int i = 0; i < c1.size(); i++) {
   System.out.print(i + " : " + c1.getValue(i) + "   \t");
   System.out.println(c2.getValue(i));
  }
 }

 public static void main(String args[]) {
  // Construct a container and randomize its content
  IntContainer original = new IntContainer(10);
  for (int i = 0; i < original.size(); i++)
   original.putValue(i, (int)(Math.random() * 100));
  try {
   // Clone the container
   IntContainer clone = (IntContainer)original.clone();
   showContainers("Before change", original, clone);  
   // Modify a value in the clone at index 1
   clone.putValue(1, clone.getValue(1) * 2);
   showContainers("After change", original, clone);
  } catch (CloneNotSupportedException e) {
   System.out.println(e.getMessage());
  }
 }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?