java - 比较 ArrayList 与 boolean 值

标签 java arraylist boolean

为什么这不起作用? 我不确定除了 Formula 之外您还需要哪些其他信息,这些信息是由 char 和 int 给出的,这构成了 Term 类型。

// returns true if f is identical to this Formula 
// e.g. terms = {Term('C',2),Term('H',6)} and f = {Term('C',2),Term('H',6)} would return true 
// but  terms = {Term('C',2),Term('H',6)} and f = {Term('H',6),Term('C',2)} would return false

public boolean identical(Formula f)
{
   int fSize = f.getTerms().size();

   if(fSize!=terms.size())
   {
       return false;
   } 
   else 
   {
       for(int j = 0; j < fSize; j++)
       {
           Term tester = terms.get(j);
           Term fTester = f.getTerms().get(j);

           if(fTester == tester)
           {
               continue;
           } 
           else 
           {
               return false;
           }
       }
   }

   return true; 
}

N.B. terms is the name of the ArrayList

最佳答案

您需要不使用 == 来比较两个对象,而是使用 equals 方法来比较对象的内容。

由于 Term 是您的自定义类,因此您需要自己重写此方法:

class Term {
  char c;  //the two values inside your Term class
  int i;

  @Override
  public boolean equals(Object o){
    //checks omitted
    Term other = (Term)o;
    //now compare the contents:
    return i==other.i && c==other.c;
  }
}

然后您可以使用它们进行比较

if(fTester.equals(tester)){
  continue;
} 

关于java - 比较 ArrayList 与 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594253/

相关文章:

java - 将变量传递给 Java 中的 ActionListener

java - 在 Matlab 中使用 Java 类

java - 如何展平数组并消除 null?

c++ - 使用 boolean 函数在 C++ 中确定所有二维点是否在线或圆上

java - 用于检查素数的 GUI

java - 在java中将 boolean 对象转换为字符串的最佳方法

java - 如何在JAVA中处理Windows XP或VISTA事件

java - 创建内存中的 FileDescriptor

java - 如何在概念上添加多态性?

java - 搜索 ArrayList