Java/Weka - Need to create unique instances

落爺英雄遲暮 提交于 2019-12-25 11:55:26

问题


I wonder if there is a method that checks whether my new instance has been already created and added to my instances in Java... Like ;

Instance instance = new Instance(i, vals);
if(instances.contains(instance) == false) { //or hasInstance maybe
    instances.add(instance);
}

回答1:


I understand, that you want for two objects x1 and x2 with x1.equals(x2) that x1 is the same instance (x1 == x2).

One needs to do something like this:

private Map<Instance, Instance> identityMap = new HashMap<>();

public Instance unique(Instance instance) {
    Instance first = identityMap.get(instance);
    if (first == null) {
        first = instance;
        identityMap.put(instance, instance);
    }
    return first;
}

Instance instance = new Instance(i, vals);
instance = unique(instance);

The reason is, that you want to maintain the first instance, to be used by all.


By the way - for other purposes:

Set<Instance> instances = ...;

Instead of

if (!instances.contains(instance)) { // if not instances contains

one could use code like

if (instances.add(instance)) {
    // Added, hence new...
} else {
    // Not added, hence already existing...
}


来源:https://stackoverflow.com/questions/23877776/java-weka-need-to-create-unique-instances

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!