在一般的開發過程中,往往要遇到從數據庫中取出數據組成值對象(通常叫做VO),然後放在列表集中,並傳回調用端的情況。在還沒有接觸到clone的時候,程序往往要在while塊中構造VO實例,但這樣做並不推薦,甚至應該極力避免,因爲會造成程序效率的低下。在使用clone技術以後,程序運行效率有所改善,以下是常用寫法,希望對大家有所幫助。
支持clone的VO看起來像這樣:
package com.XXX;
import java.util.*;
public class TempJob implements Cloneable { //聲明其可被clone
private String Jbnr=null;
private String Jbdw=null;
public Object clone() {
try {
return super.clone(); //返回clone以後的對象
}
catch (CloneNotSupportedException e) {
System.out.println(e.toString());
}
public void setJbnr(String Jbnr){
this.Jbnr=Jbnr;
}
public String getJbnr(){
return Jbnr;
}
public void setJbdw(String Jbdw){
this.Jbdw=Jbdw;
}
public String getJbdw(){
return Jbdw;
}
}
對於調用VO的類,像這樣:
package com.XXX;
import java.sql.*;
import java.util.*;
public class DoJob{
private Connection con;
private Statement stmt;
private ResultSet rs;
private ArrayList lis=new ArrayList();
public ArrayList query(String a){
String sql="";
sql="select a.*,b.name from temp_job a, user_basic b "
+"where a.userid = b.userid order by a.wcqk";
try{
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
TempJob job=new TempJob(); //只要一個實例
while (rs.next()){
job.setJbnr(rs.getString(1));
job.setJbdw(rs.getString(2));
lis.add(job.clone()); //返回被clone對象
}
}
catch(SQLException e){
System.out.println(e.toString());
}
finally {
this.rs=null;
this.stmt=null;
con.close();
}
return lis;
}
}
(請注意!引用、轉貼本文應註明原作者:Rosen Jiang 以及出處:http://blog.csdn.net/rosen)