導航:首頁 > 編程語言 > java克隆

java克隆

發布時間:2021-12-04 07:08:24

『壹』 java 對象克隆什麼時候用

個人覺得,我們編程需要克隆的並不多,但是程序之間方法的調用、參數的傳遞是會使用克隆的。比如函數參數類型是自定義的類時,便是引用傳遞而不是值傳遞,這時候便克隆對象了一般用到的地方,是為了不破壞原對象的屬性,在這個基礎上創建新的克隆對象進行操作的安全性就能得到提高了

『貳』 java里的克隆重要嗎

假如你是來新人的話,可以自不看,或者略微過下就行了
(可以以後等積累了一些經驗再看,那樣理解快)

如果有幾年工作經驗,想深造的話,還是仔細看看,裡面有幾個點是要注意的
不然真在工作遇到,不了解的話不比較麻煩

克隆其實功能還是很好的,只是很多人不懂細節,所以一般不用
但我現在在用,為什麼有好功能不用

『叄』 Java中是如何實現克隆

java 實現clone對象方法抄的步驟如下:
(1)實現Cloneable介面
(2)重載Object類中的clone()方法,重載時需定義為public
(3)在重載方法中,調用super.clone()
例如:
class CloneClass implements Cloneable {
public int aInt;

public Object clone() {
CloneClass o = null;
try {
o = (CloneClass) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}

『肆』 java對象之間如何實現克隆(復制)

用clone()方法,不過在對象重載了Object的clone才能用。Object的clone方法是protected。

『伍』 java對象克隆

修改後的代碼

classBook1implementsCloneable{
privateStringtitle;
privatedoubleprice;
publicBook1(Stringtitle,doubleprice){
this.title=title;
this.price=price;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicdoublegetPrice(){
returnprice;
}
publicStringgetTitle(){
returntitle;
}
protectedObjectclone(){
returnsuper.clone();
}
publicStringtoString(){
return"BOOK[title="+title+",price="+price+"]";
}
}
publicclassX{
publicstaticvoidmain(Stringargs[]){
Book1bookA=newBook1("JAVA從入門到精通",79.8);
Book1bookB;
try{ //加一個異常處理
bookB=(Book1)bookA.clone();
bookB.setPrice(100.8);
System.out.println(bookA);
System.out.println(bookB);
}catch(Exceptione){
}
}
}

『陸』 java如何實現對象的克隆

可以重載clone方法克隆對象

首先、該類要實現Cloneable的介面,不然執行clone方法內的時候會拋出CloneNotSupportedException異常

然後容、就在該類重載clone方法,自己加上克隆的邏輯,本人小白,手敲的代碼

{

privateStringname;

publicBook(Stringname){
this.name=name;
}

@Override
publicBookclone(){
returnnewBook(this.name);
}
}

『柒』 java 如何拷貝

package czday0017;

import java.io.*;
import java.util.*;
/** IO 工具類 */
public class IO {
/**
* 獲取目錄的全部文件
* @param dir
* @return
*/
public static List<File> listFile(File dir){
return null;
}
/**
* 獲取目錄的全部文件, 指定擴展名的文件
* @param dir
* @return
*/
public static List<File> listFile(
File dir, String ext){
return null;
}
/**
* 遞歸獲取目錄的全部文件
* @param dir
* @return
*/
public static List<File> listAll(
File dir){
return null;
}
/**
* 遞歸獲取目錄的全部文件, 指定擴展名的文件
* @param dir
* @return
*/
public static List<File> listAll(
File dir, String ext){
return null;
}

/**
* 復制文件
*/
public static void cp(String from, String to)
throws IOException {
cp(new File(from), new File(to));
}
/**
* 復制文件
*/
public static void cp(File from, File to)
throws IOException {
cp(new FileInputStream(from),
new FileOutputStream(to));
}
/**
* 復制文件
*/
public static void cp(InputStream in,
OutputStream out)
throws IOException {
//1K byte 的緩沖區!
byte[] buf = new byte[1024];
int count;
while((count=in.read(buf))!=-1){
System.out.println(count);
out.write(buf, 0, count);
}
in.close();
out.close();
}
/**
* 從流中讀取一行文本, 讀取到一行的結束為止
* @param in
* @return 一行文本
*/
public static String readLine(
InputStream in, String charset)
throws IOException{
byte[] buf = {};
int b;
while(true){
b = in.read();
if(b=='\n' || b=='\r' || b==-1){//編碼是否是回車換行
break;
}
buf=Arrays.Of(buf, buf.length+1);
buf[buf.length-1]=(byte)b;
}
if(buf.length==0 && b==-1)
return null;
return new String(buf,charset);
}

/**
* 讀取文件的全部內容到一個byte數組
* 可以緩存一個"小"文件到堆內存中
*/
public static byte[] read(String filename)
throws IOException{
return read(new File(filename));
}
/**
* 讀取文件的全部內容到一個byte數組
* 可以緩存一個"小"文件到堆內存中
*/
public static byte[] read(File file)
throws IOException{
//用RAF打開文件
RandomAccessFile raf =
new RandomAccessFile(file, "r");
//安裝文件的長度開辟 緩沖區數組(byte數組)
byte[] buf = new byte[(int)raf.length()];
//讀取文件的緩沖區
raf.read(buf);
//關閉文件(RAF)
raf.close();
//返回緩沖區數組引用.
return buf;
}
/**
* 讀取文件的全部內容到一個byte數組
* 可以緩存一個"小"文件到堆內存中
* 如: 文件內容: ABC中 讀取為: {41, 42, 43, d6, d0}
*/
public static byte[] read(InputStream in)
throws IOException{
byte[] ary = new byte[in.available()];
in.read(ary);
in.close();
return ary;
}
/**
* 連接byte 數組的全部內容為字元串,
* 以hex(十六進制)形式連接
* 如: 數組{0x41, 0x42, 0x43, 0xd6, 0xd0}
* 結果: "[41, 42, 43, d6, d0]"
*/
public static String join(byte[] ary){
if(ary==null || ary.length==0)
return "[]";
StringBuilder buf =
new StringBuilder();
buf.append("[").append(
leftPad(Integer.toHexString(ary[0]&0xff),'0',2));
for(int i=1; i<ary.length; i++){
String hex=Integer.toHexString(ary[i]&0xff);
buf.append(",").append(leftPad(hex,'0',2));
}
buf.append("]");
return buf.toString();
}

public static String toBinString(byte[] ary){
if(ary==null || ary.length==0)
return "[]";
StringBuilder buf =
new StringBuilder();
buf.append("[").append(
leftPad(Integer.toBinaryString(ary[0]&0xff),'0',8));
for(int i=1; i<ary.length; i++){
String hex=Integer.toBinaryString(ary[i]&0xff);
buf.append(",").append(leftPad(hex,'0',8));
}
buf.append("]");
return buf.toString();
}
/**
* 實現leftPad功能, 對字元串實現左填充
* @param str 被填充字元串: 5
* @param ch 填充字元: #
* @param length 填充以後的長度: 8
* @return "#######5"
*/
public static String leftPad(
String str, char ch, int length){
if(str.length() == length){
return str;
}
char[] chs = new char[length];
Arrays.fill(chs, ch);
System.array(str.toCharArray(), 0, chs,
length - str.length(), str.length());
return new String(chs);
}
/**
* 將text追加到文件 filename的尾部
* 使用系統默認文本編碼
*/
public static void println (
String filename, String text)
throws IOException{
println(new File(filename),text);
}
public static void println(
File file, String text)throws IOException{
OutputStream out = new FileOutputStream(file,true);
println(out, text);
out.close();
}
/**
* 向流中輸出一行字元串, 使用默認編碼
* 不關閉流
* @param out 目標流
* @param text 文本
* @throws IOException
*/
public static void println(
OutputStream out, String text)throws IOException{
out.write(text.getBytes());
out.write('\n');
}
/**
* 向流中輸出一行字元串, 使用指定的編碼
* 不關閉流
* @param out 目標流
* @param text 文本
* @param charset 指定的編碼
* @throws IOException
*/
public static void println(
OutputStream out, String text, String charset)throws IOException{
out.write(text.getBytes(charset));
out.write('\n');
}
/**
* 文件切分
* @param file
* @param size
* @throws IOException
*/
public static void spilt(String file,int size) throws IOException{
if(size<=0){
throw new IllegalArgumentException("干嗎啊!輸入有誤阿!");
}
int idx = 0;//文件序號
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(new FileOutputStream(file+"."+idx++));
int b;
int count = 0;
while((b = in.read())!=-1){
out.write(b);
count++;
if(count%(size*1024)==0 ){
out.close();
out = new BufferedOutputStream(new FileOutputStream(file+"."+idx++));
}
}
in.close();
out.close();
}
/**
* 將文件進行連接
* @param filename是一個文件名;如:file.dat.0
*/
public static void join(String file)throws IOException{
String filename = file.substring(0, file.lastIndexOf("."));
String num = file.substring(file.lastIndexOf(".")+1);
int idx = Integer.parseInt(num);
OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
File f = new File(filename+"."+idx++);
while(f.exists()){
InputStream in = new BufferedInputStream(new FileInputStream(f));
cp(in,out);
in.close();
f = new File(filename+"."+idx++);
}
out.close();
}
/**
* 序列化對象
*/
public static byte[] Serialize(Serializable obj)throws IOException{
return null;
}

public static Object unSerializable(byte[] data)throws IOException{
return null;
}

public static Object clone(Serializable obj)throws IOException{
return unSerializable(Serialize(obj)) ;
}
}

//使用cp工具!

『捌』 java中的克隆技術具體有什麼應用

Clone基本知識儲備
在Java里提到clone技術,就不能不提java.lang.Cloneable介面和含有clone方法的Object類。所有具有clone功能的類都有一個特性,那就是它直接或間接地實現了Cloneable介面。否則,我們在嘗試調用clone()方法時,將會觸發CloneNotSupportedException異常。 下面我們通過對Object類的部分源碼的分析,來發現和理解這一特性。
l clone的實現

1.實現Cloneable介面

通過上一篇的介紹,我們知道,一個類若要具備clone功能,就必須實現Cloneable介面。做到這一步,clone功能已經基本實現了。Clone功能對我們來說,最主要的還是要能夠使用它。那麼我們如何才能使用clone功能呢?答案是覆蓋Object#clone()方法。

2. 覆蓋Object#clone()方法

為什麼需要覆蓋Object#clone()方法?這里得再次從jdk源碼說起。JDK中Object# clone()方法的原型是:

protected native Object clone() throws CloneNotSupportedException;

是否注意到,這里clone()方法修飾符是protected,而不是public。這種訪問的不可見性使得我們對Object#clone()方法不可見。相信讀者已明白為什麼要覆蓋Object#clone()方法。而且,覆蓋的方法的修飾符必須是public,如果還保留為protected,覆蓋將變得沒有實際意義。下面舉一個具有clone功能的簡單的例子:

/*

* 具有clone功能的類的例子

*/

public class CloneableObjExample implements Cloneable {

//……部分代碼已省略……

private String name = null;

private int score = 0;

/**

* NOTE: 將protected 修飾符 更改為 public

* @see java.lang.Object#clone()

*/

public/*protected*/ Object clone() throws CloneNotSupportedException {

// call父類的clone方法

Object result = super.clone();

//TODO: 定製clone數據

return result;

}

}

3.定製clone

至此,clone已經真相大白。Clone的對象我們可以對其進行定製。還就上面的例子來說。下面的方法對功能做了一定的增強:

public/*protected*/ Object clone() throws CloneNotSupportedException {

// call父類的clone方法

CloneableObjExample result = (CloneableObjExample)super.clone();

//TODO: 定製clone數據

//雖然」clone」了,但還可以做點調整

result.name = 「New Name」;

result.score = 90;

return result;

}

本篇介紹了如何實現clone。接下來的篇幅將就縱深clone等clone的高級特性進行分析。

本章將進入clone的高級特性,著重講述縱深clone技術。

Clone通常有兩種類型即淺clone和深clone。首先,分析一下兩種的不同。淺clone和深clone都是clone,它們本質區別是對象內部的成員屬性(非原生類型屬性,如int等)在clone時是否處理為引用。如果仍然保留為引用,則稱為淺clone,反之稱為深clone。其實這兩個概念也是相對的概念。在處理上它們有點區別,淺clone方式得到clone對象即可,深clone方式在得到clone對象後,還需要對引用的成員屬性進行「clone」處理。從這個層次上說,深clone並沒有什麼特別地困難,簡單講就是創建好對象,再設置一些成員屬性。關於深clone,網上的文章已經有太多,有點目不暇接的感覺,本文不再贅述,這也不是本文的重點。

本文的重點是要闡述縱深clone,亦即「N深clone」。深到什麼程度為止?本文描述的目標是一直深到你想要的程度,包括深到不能再深的程度。

『玖』 java 對象 克隆

這是裡面的一段(非完整的例子):
public class Snake implements Cloneable {

...........................

public Object clone() {
Object o = null;
try {
o = super.clone();
} catch (CloneNotSupportedException e) {}
return o;

}
書上一段給你看看,希望有幫助把。。
當製作實例變數的一個引用時,原始實例變數和副本實力變數在內存中引用的均是同一個存儲空間,這就意味著但對其中一個實例變數操作時就會影響到這個對象的副本。例如下面的程序代碼。在執行時將會看到所畫的兩條線重合在一起,都是改變後的LineFigure1。
LineFigure lineFigure1 = new LineFigure();
LineFigure lineFigure2 = lineFigure1;
lineFigure1.draw(g);
…code for changing lineFigure1
lineFigure2.draw(g);
如果想讓LineFigure2成為一個新的對象,就要用到Clone( )方法。Clone的後對象和原對象的存儲空間不同,改變其中一個並不會對另一個產生任何影響。例如下面代碼所示:
…………….
LineFigure2 = lineFigure1.clone();
…………….
如果LineFigure2中沒有對其他對象的引用,事情就到此結束了,但LineFigure類中的實例變數StartPoint和EndPoint都是一個對象,即使簡單地實現了對LineFigure1地Clone,可LineFigure1和LineFigure2的StartPoint和EndPoint實例變數引用的是同一個變數,要想完全的實現將LineFigure2和LineFigure1分離開,就要實現Cloneable介面,並重寫Clone方法。Cloneable介面是Java提供的少數幾個標簽化介面之一。平常所說的標簽化介面就是不提供任何方法的介面。在圖形白板程序中,也用到了Cloneable介面,例如LineFigure類中的代碼:
public class LineFigure extends Figure implements Cloneable{
public Object clone(){
LineFigure lineFigure = new LineFigure();
lineFigure.startPoint = (Point)startPoint.clone();
lineFigure.endPoint = (Point)endPoint.clone();
lineFigure.firstDraw = firstDraw;
return lineFigure;
}
………………..
}
這樣一來,LineFigure1和LineFigure2所引用的對象就沒有任何的重合。對其中任何一個進行修改而不影響另一個的應用。

『拾』 如何克隆Java對象

Java中的對象涉及使用引用類型,沒有直接的方法可將一個對象的內容復制到一個新對象中。將一個引用分配給另一個引用只會給相同對象建立另一個引用。因此,Java對所有引用類型使用一個特殊的clone()方法,為對象復制自身提供一個標準的機制。以下是你需要了解和克隆Java對象有關的細節。為何建立一個本地拷貝?給一個對象建立本地拷貝的原因很可能是由於你計劃修改該對象,並且你不想修改方法調用者的對象。如果你確定你需要一個本地拷貝,你可以使用Object類的clone()方法來執行這項操作。clone()方法被定義為受保護方法,但你必須在你希望克隆的所有子類中重新公開定義它。例如,標准庫類ArrayList忽略clone(),但你可以這樣為ArrayList調用clone()方法:import java.util.*;class MyInt {private int i;public MyInt(int ii) { i = ii; }public void increment() { i++; }public String toString() {return Integer.toString(i);}}public class Test {public static void main(String[] args) {ArrayList al = new ArrayList();for(int i = 0; i < 10; i++ )al.add(new MyInt(i));ArrayList al1 = (ArrayList)al.clone();// Increment all al1』s elements:for(Iterator e = al1.iterator(); e.hasNext(); ) ((MyInt)e.next()).increment();}}clone()方法生成一個Object,它必須重新轉變為適當的類型。這個例子說明ArrayList的clone()方法如何不能自動克隆ArrayList包含的每一個對象?原有ArrayList和克隆後的ArrayList是相同對象的別名。這種情況通常叫做淺拷貝,因為它僅僅復制一個對象的「表面」部分。實際的對象由這個「表面」,引用指向的所有對象,以及那些對象指向的所有對象等構成。這往往被稱作「對象網路」。下一頁>>

閱讀全文

與java克隆相關的資料

熱點內容
歐美電影學生愛上女快遞員 瀏覽:360
匯編實驗循環程序實驗 瀏覽:574
武俠肉版小說 瀏覽:428
蘋果市值2014 瀏覽:48
根據文件名提取文件軟體 瀏覽:211
win10文件夾變粉色 瀏覽:608
富家千金小倉電影 瀏覽:874
看好片網址 瀏覽:938
日本大胸的女人電影 瀏覽:475
魔鬼交鋒 .45 瀏覽:469
男女生猴子的電影 瀏覽:439
win10共享文件密碼怎麼取消 瀏覽:551
大數據崗位人才缺口多少 瀏覽:772
面向對象程序設計的基本概念 瀏覽:147
itv怎麼刪除app 瀏覽:839
蘋果137去除小紅點描述文件 瀏覽:917
蘋果11描述文件跳不出來 瀏覽:51
js實現按鈕單擊事件 瀏覽:98
app改國家在哪裡 瀏覽:832
招標文件有下列哪些情形招標人應當拒收 瀏覽:610

友情鏈接