你的目的就是要每个实例都有自己专有属性。很简单,把attValue和attName属性移到Tuple里就可以了。特别提醒一下:在JAVA里面,抽象的往往是行为而不是属性。比如 interface TupleInterface { public List getAttName(); public List getAttValue(); }
interface TupleInterface { public List getAttName(); public List getAttValue(); }public class Tuple implements TupleInterface { private List attName; private List attValue; public Tuple() { }}
晕……前面按错键了public class Tuple implements TupleInterface { private List attName; private List attValue; public Tuple() { this.attName = new ArrayList(); this.attValue = new ArrayList(); } public List getAttName() { return this.attName; } public List getAttValue() { return this.attValue; } ...}调用的时候: TupleInterface tuple = new Tuple(); tuple.getAttName(); tuple.getAttValue();
interface TupleInterface {
ArrayList attName=new ArrayList();
ArrayList attValue=new ArrayList();
}
public class Tuple implements TupleInterface{
}这是我自己定义的一个tuple类,然后一个scan的函数:
while(resultSet.next()){
ArrayList temp=new ArrayList();
tupleNo++;
for(int p=1;p<=nColumns;p++){
String val=resultSet.getString(p);
Object obj=(Object)val;
temp.add(obj);
}
tuple.attValue.add(temp);
} return tuple;
}发现每次调用scan时,都会累加在之前的结果上。还有,刚发现不管在哪个函数里,只要新建一个tuple对象,就会默认给这个新建的对象赋值为当前另外一个tuple对象的值!这是怎么回事?是不是tuple类的定义有错误?谢谢!
ArrayList attName=new ArrayList();
而不能写
ArrayList attName;static属性会在所有实现了TupleInterface的对象之间共用。所以新建一个对象也会接受老对象的属性。在while之前调用
attName.clear();
attValue.clear();
应该可以解决结果累加的问题。
interface TupleInterface {
public List getAttName();
public List getAttValue();
}
public List getAttName();
public List getAttValue();
}public class Tuple implements TupleInterface {
private List attName;
private List attValue; public Tuple() { }}
private List attName;
private List attValue; public Tuple() {
this.attName = new ArrayList();
this.attValue = new ArrayList();
} public List getAttName() {
return this.attName;
} public List getAttValue() {
return this.attValue;
} ...}调用的时候:
TupleInterface tuple = new Tuple();
tuple.getAttName();
tuple.getAttValue();
Tuple tuple=new Tuple();
TupleInterface说是invisible的