很多情况很多朋友写JAVA的时候都会自定义对象,但有时为了方便测试都会直接new一个匿名对象,比如当我们用到Vector这个类储存数据时,代码;
import java.util.Vector;
class vectorClient{
private String name;
private String ip;
public vectorClient( String name , String ip ){
this.name = name;
this.ip = ip;
}
public String toString(){
return “【”+name+”】”+ip;
}
}
class test_vector{
public static void main(String [] args){
Vector<vectorClient> vt = new Vector<vectorClient>();
vt.add( new vectorClient(“A1″,”127.0.0.1″));
vt.add( new vectorClient(“A2″,”127.0.0.2″));
vt.add( new vectorClient(“A3″,”127.0.0.3″));
vt.add( new vectorClient(“A4″,”127.0.0.4″));
//比如我要删除A4这个名字的vectorClient对象
vt.removeElement( new vectorClient(“A4″,”127.0.0.4″) );
System.out.println(vt);
}
}
大家看到了,这样removeElement() 是没用的,因为每一个自定义的类都是默认继承java.lang.Oject这个类,这个类有一个方法是 equal() 。我们需要重写这个方法才能判断我们所比较的对象是否相等,如果不重写的话,系统是不会比较我们自定的 name 和 ip的,系统会根据这个对象所在的内存地址来作为比较。这样的话我们所构造的vectorClient对象就不能匿名,我们要删除的话只能如下代码:
vectorClient vc1 = new vectorClient(“A4″,”127.0.0.4″);
vt.add(vc1);
vt.removeElement(vc1);
这样的话就能删除了,因为用的是同一个引用就是同一个地址。
import java.util.Vector;
class vectorClient{
private String name;
private String ip;
public vectorClient( String name , String ip ){
this.name = name;
this.ip = ip;
}
public String toString(){
return “【”+name+”】”+ip;
}
//在自定义的类加多下面这种方法
public boolean equals(Object obj){
vectorClient vc = (vectorClient)obj;
if( vc.name.equals(name) && vc.ip.equals(ip) ){
return true;
}
return false;
}
}
class test_vector{
public static void main(String [] args){
Vector<vectorClient> vt = new Vector<vectorClient>();
vt.add( new vectorClient(“A1″,”127.0.0.1″));
vt.add( new vectorClient(“A2″,”127.0.0.2″));
vt.add( new vectorClient(“A3″,”127.0.0.3″));
vt.add( new vectorClient(“A4″,”127.0.0.4″));
//比如我要删除A4这个名字的vectorClient对象
vt.removeElement( new vectorClient(“A4″,”127.0.0.4″) );
System.out.println(vt);
}
}
重点:
当调用remove方法的时候,系统会自动调用equals()方法来检测这个对象是否为要删除的对象。
转载请注明:乔布尸 » 自定义对象new一个匿名对象以后,removeElement 对象的操作瓶颈