问题
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