gpt4 book ai didi

java - Java中基于权重的对象匹配(不是内存中对象的实际权重)

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:11 26 4
gpt4 key购买 nike

我正在尝试找到一种很好的设计来衡量对象中的属性。

例如;

对象“A”可以有 4 个字段,所有字段的权重都不同(对于此示例,字段的权重将均匀)。找到一个相同类型的新对象,并且只有部分字段是相同的。对于此示例,对象“B”的 2 个字段等于对象“A”。所以它与对象“A”有 50% 相同。

代码中的另一个示例;

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

}

}

我想要一种方法来表示该对象具有相同的值,但属性的权重可以改变。

我希望这是有道理的,所以简而言之,我想要一个解决方案,其中可以对对象的每个属性进行加权,并且当对两个对象执行 equals 时,会返回一个值,表示该对象的值相同。

最佳答案

您可以创建在运行时可用的注释:

@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;
}
}

关于java - Java中基于权重的对象匹配(不是内存中对象的实际权重),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20049196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com