gpt4 book ai didi

java - 如何比较对象数组中的对象?

转载 作者:行者123 更新时间:2023-12-02 12:08:59 25 4
gpt4 key购买 nike

我已经从 Cube 类型创建了一个对象。

public Cube (int lengthOfEdge, String color)
{
this.lengthOfEdge= lengthOfEdge;
this.color = color;
}

此外,我创建了 4 个不同的立方体,并将两个立方体放入两个不同的数组中。我想比较数组以查看它们是否完全相同,我的意思是 arr1[1] 中的立方体是否与 arr2[1] 中的立方体相似。我该怎么做?

我正在尝试使用我创建的比较方法。

public boolean equals(Cube c)
{
if(this.getLengthOfEdge()==c.getLengthOfEdge() && this.getColor()==(c.getColor()))
return true;
return false;
}

最佳答案

您可以使用System.Reflection来比较对象的属性。对于您的示例,您可以创建一个函数,如下所示,然后将对象简单地传递给该函数

       public static  bool Compare(Cube f, Cube s)
{
bool returnVal = true;
foreach (var item in f.GetType().GetProperties())
{
if(!f.GetType().GetProperty(item.Name).GetValue(f).Equals(s.GetType().GetProperty(item.Name).GetValue(s)))
{
returnVal = false;
}
}
return returnVal;
}

关于java - 如何比较对象数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692453/

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