Java中基于权重的对象匹配(不是内存中对象的实际权重)
我正试图找到一个很好的设计来加权对象中的属性 比如, 对象“A”可能有4个字段,所有字段的权重都不同,因为此示例中的字段将均匀加权。找到了一个相同类型的新对象,并且只有部分字段相同。对于本例,对象“B”的2个字段等于对象“A”。因此,它与对象“A”相同50% 代码中的另一个示例Java中基于权重的对象匹配(不是内存中对象的实际权重),java,Java,我正试图找到一个很好的设计来加权对象中的属性 比如, 对象“A”可能有4个字段,所有字段的权重都不同,因为此示例中的字段将均匀加权。找到了一个相同类型的新对象,并且只有部分字段相同。对于本例,对象“B”的2个字段等于对象“A”。因此,它与对象“A”相同50% 代码中的另一个示例 Class Person{ {Weight = 60} String name; {Weight = 20} String address; {Weight = 20}
Class Person{
{Weight = 60}
String name;
{Weight = 20}
String address;
{Weight = 20}
int age
int weightBasedEqual(Person a, Person b)
{
//based on my weights I want to pass two Person objects and get a weighted value back
//So in my example the names are the same but the two other fields are incorrect,
//but based on my weights it will return 60 as the match, where 100 was the top weight.
return value
}
}
我想用一种方法说这个对象的值是相同的,但是属性的权重可以改变
我希望这是有意义的,所以简言之,我想要一个解决方案,其中一个对象的每个属性都可以加权,当对两个对象执行相等操作时,返回一个值,表示该对象的值相同。您可以创建和注释,该值将在运行时可用:
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({FIELD})
@Inherited
@interface Weight{
int value();
}
然后您可以注释类的字段
public class TestBean{
@Weight(20)
int field1;
@Weight(80)
int field2;
}
然后实现一种方法,该方法将对所有具有该注释的字段执行某些操作:
int weightBasedEqual(Person a, Person b)
// For each field annotated with @Weight
for(Field field : a.getClass().getDeclaredFields()){
if(field.isAnnotationPresent(Weight.class)){
// Get the weight
int weight = field.getAnnotation(Weight.class).value();
Object valueFromA = field.get(a); // Get field value for A
Object valueFromB = field.get(b); // Get field value for B
// Compare the field value from 'a' and 'b' here and do with the weight whatever you like
}
}
return result;
}
}
这里有一种计算weightBasedEqual的方法
public class Person {
String name;
static int nameWeight = 60;
String address;
static int addressWeight = 20;
int age;
static int ageWeight = 20;
public int weightBasedEqual(Person a, Person b) {
int value = 0;
if (a.name.equalsIgnoreCase(b.name)) {
value += nameWeight;
}
if (a.address.equalsIgnoreCase(b.address)) {
value += addressWeight;
}
if (a.age == b.age) { value += ageWeight; }
return value;
}
public int weightBasedEqual(Person b) {
return weightBasedEqual(this, b);
}
}
当且仅当字段完全匹配时,该函数通过为每个字段添加权重来工作。如所写,函数将返回0、20、40、60、80或100
请注意,每个Person类有一个nameWeight、addressWeight和ageWeight,因为它是静态的
我添加了第二个weightBasedEqual,只有一个人,因为可能有时需要根据现有对象计算重量相等。不,你的要求没有真正意义。