gpt4 book ai didi

java - 在列表中查找,然后分配给一个变量,如果结果已存在于另一个变量中,则返回 null

转载 作者:太空宇宙 更新时间:2023-11-04 09:51:50 25 4
gpt4 key购买 nike

我有两个变量和一个列表,我正在查找要分配给变量的项目:

var_A = tl_1;

var_B = findFirst(ground.getTargetLines(), n->n.getName().equals("tl_1"));

如果我对 var_B 执行的查找包含与 var_A 相同的结果,则我得到 null。如果 var_A 为空或包含不同的值,则可以将查找结果分配给 var_B。

请问我缺少什么?

最佳答案

有问题的部分

这里的问题是 AnyLogic 类型的 getName() 函数的行为。

我尝试了 TargetLine 类型(从 com.anylogic.engine.markup.AbstractMarkup 继承 getName()),也尝试了 RectangleShape(从 com.anylogic.engine.presentation.Shape 继承 getName()),它们的行为都是相同的。

AnyLogic 文档对 ShapegetName() 的解释如下:

getName(): If the shape is declared as field in a presentable object class (Agent or Experiment), e.g. if it was drawn in the graphical editor, returns the name of the field, otherwise returns the string UNKNOWN_NAME.

TargetLinegetName() 的解释类似。

意外行为

当您将 TargetLineRectangleShape 的实例或其他 AnyLogic 特定类的实例分配给 AnyLogic(!) 变量(意味着在 Canvas 上以图形方式定义的变量)时,getName() 的结果将从图形编辑器中该实例属性中定义的名称更改为分配给它的变量的名称。从这一刻起,您可以不再检索最初定义的名称,因为它已在内部更改为变量的名称。但实例仍然是相同的,只是 getName() 函数的返回值发生了变化。

以下是该行为的示例: AnyLogic GUI

traceln(rectangle.getName()); //prints "rectangle"
myRectangle = rectangle; //assign to AnyLogic Variable
traceln(rectangle.getName()); //prints "myRectangle"

这解释了为什么在您将按名称搜索的列表成员分配给 AnyLogic 变量后,您的 lambda 表达式(以及使用 getName() 函数的简单循环)将无法按预期工作。

可能的解决方法

  • 不将您正在搜索的对象分配给 AnyLogic 变量(您可以使用普通的 Java 变量,效果很好)
  • 通过将此信息存储在 Java 映射或类似文件中,并在按名称搜索实例时访问此资源,自行跟踪名称-实例配对

结论

总而言之,AnyLogic 文档应该说明的内容更像是这样:

getName(): If the shape is declared as field in a presentable object class (Agent or Experiment), e.g. if it was drawn in the graphical editor, returns the name of the field, otherwise returns the string UNKNOWN_NAME. If the shape is being assigned to an AnyLogic variable (a variable drawn in the graphical editor), returns the name of this variable instead. Eg. after running the code myVar = myShape;, getName() will return myVar instead of myShape.

关于java - 在列表中查找,然后分配给一个变量,如果结果已存在于另一个变量中,则返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54636702/

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