2013-07-16 34 views
1

我尝试使用OberservableLists contains函数来检查给定元素是否已经在列表中,如果不添加它。 我的代码如下所示:ObservableList#contains()为现有项目返回false

ObservableList<Device> devicesScannerList = FXCollections.observableArrayList() 
deviceScannerList.add((Device)dev); 

后来我做

Device dev = (Device)devices.get(0); 
boolean deviceExists = devicesScannerList.contains(dev); 
if (deviceExists){....} 

的问题是,deviceExists永远是假的,但我可以在devicesScannerList已经包含了给定的设备和我don`调试模式看我想再次添加它。

我是否误解了包含函数? 帮助将是巨大的

THX 英戈

回答

3

确保您Device类正确实现equalshashCode方法。

E.g.如果您使用完全相同的数据创建2个Device对象,则除非Device实施了equals/hashCode,否则它们将不会被ObservableArrayList(或任何列表)视为相同。

见下面的例子:

public class ObsListTest { 

    static class Device { 
     int value; 

     public Device(int value) { 
      this.value = value; 
     } 
    } 

    public static void main(String[] args) { 
     ObservableList<Device> list = FXCollections.<Device>observableArrayList(); 
     Device data1 = new Device(1); 
     Device anotherData1 = new Device(1); 
     list.add(data1); 
     System.out.println(list.contains(data1)); // true 
     System.out.println(list.contains(anotherData1)); // false 
    } 
} 

但这个代码就可以了(打印true两次),如果你旁边添加到设备:

 @Override 
     public boolean equals(Object obj) { 
      if (obj == null || getClass() != obj.getClass()) { 
       return false; 
      } 
      return this.value == ((Device) obj).value; 
     } 

     @Override 
     public int hashCode() { 
      return 7 + 5*value; // 5 and 7 are random prime numbers 
     } 

这里查看更多详细信息:What issues should be considered when overriding equals and hashCode in Java?

+0

THX非常!这就是诀窍:) – Inge