package com.ngaa.test; import java.util.ArrayList; import java.util.HashMap; /** * @author Created by yangjf on 20180801. * Update date: * Time: 11:30 * Project: dev-spark01-examples * Package: com.ngaa.test * Describe : java浅copy和深co
package com.ngaa.test;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Created by yangjf on 20180801.
* Update date:
* Time: 11:30
* Project: dev-spark01-examples
* Package: com.ngaa.test
* Describe : java浅copy和深copy
* 原文链接:http://canofy.iteye.com/blog/258790
* Frequency:
* Result of Test: test ok
* Command:
* <p>
* Email:
* Status:Using online
* <p>
* Please note:
* Must be checked once every time you submit a configuration file is correct!
* Data is priceless! Accidentally deleted the consequences!
*/
public class CopyStringTest {
public static void main(String args[]) {
/** 浅拷贝与深拷贝 */
/* 1、浅拷贝
被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。
换言之,浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
*/
/* 2、深拷贝
被复制对象的所有变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。
那些引用其他对象的变量将指向被复制过的新对象,而不再是原有的那些被引用的对象。
换言之,深复制把要复制的对象所引用的对象都复制了一遍。
*/
/* 3、分类
(1)直接赋值(字符串外都属于浅拷贝)
(2)使用构造函数(深拷贝)
(3)使用clone()方法(深拷贝)
*/
/* 字符串(不理解无colne()方法) */
String s = "sss";
String t = s; //深拷贝
String y = new String(s); //深拷贝
System.out.println("s:" + s + " t:" + t + " y:" + y);
t = "ttt";
y = "yyy";
System.out.println("s:" + s + " t:" + t + " y:" + y);
/* 数组 */
String[] ss = {"111", "222", "333"};
String[] tt = ss; //浅拷贝
String[] ww = (String[]) ss.clone(); //深拷贝
System.out.println("ss:" + ss[1] + " tt:" + tt[1] + " ww:" + ww[1]);
tt[1] = "2t2";
ww[1] = "2w2";
System.out.println("ss:" + ss[1] + " tt:" + tt[1] + " ww:" + ww[1]);
/* list列表 */
ArrayList<String> a = new ArrayList<>();
for (int i = 0; i < 10; i++) {
a.add(String.valueOf(i + 1));
}
ArrayList<String> b = a; //浅拷贝
ArrayList<String> c = new ArrayList<>(a); //深拷贝
ArrayList d = (ArrayList) a.clone(); //深拷贝
System.out.println("a:" + a.get(1) + " b:" + b.get(1) + " c:" + c.get(1) + " d:" + d.get(1));
b.set(1, "bbb");
c.set(1, "ccc");
System.out.println("a:" + a.get(1) + " b:" + b.get(1) + " c:" + c.get(1) + " d:" + d.get(1));
/* HashMap */
HashMap<String,String> h = new HashMap<>();
h.put("1", "hhh");
HashMap<String,String> m = h; //浅拷贝
HashMap<String,String> p = new HashMap<>(h); //深拷贝
HashMap<String,String> n = (HashMap) h.clone(); //深拷贝
System.out.println("h:" + h.get("1") + " m:" + m.get("1") + " p:" + p.get("1") + " n:" + n.get("1"));
m.put("1", "mmm");
p.put("1", "ppp");
n.put("1", "nnn");
System.out.println("h:" + h.get("1") + " m:" + m.get("1") + " p:" + p.get("1") + " n:" + n.get("1"));
}
}
【感谢龙石数据为本站数据中台建设方案 http://www.longshidata.com/pages/government.html,感恩 】