【问题标题】:trying to compare object cannot use IF statement JAVA试图比较对象不能使用 IF 语句 JAVA
【发布时间】:2023-03-03 11:52:01
【问题描述】:

我正在编写一种在 ArrayList 中查找对象的方法。如果我能找到对象,我会将其打印到屏幕上,否则我将打印一条错误消息,指出“找不到对象”。我遇到的问题是因为我的方法是对象“十二面体”,而不是布尔值,所以我不能使用 if 语句来比较对象是否存在于数组中。我还能如何处理这个问题?

这是我的 main 方法中的代码。

    System.out.print("\tLabel: ");
    label = userInput.nextLine();

    if(myDList.findDodecahedron(label)) {

        System.out.print(myDList.findDodecahedron(label));
    }
    else {
        System.out.print("\t\"" + label + "\" not found");
    }
        System.out.print("\n\nEnter Code [R, P, S, A, D, F, E, or Q]: ");
    break;

这是我的方法。

public Dodecahedron findDodecahedron(String label1In) {
      String label = "";
      String color = "";
      double edge = 0;
      Dodecahedron result = new Dodecahedron(label, color, edge);
      int index = -1;
      for (Dodecahedron d : dList) {
         if (d.getLabel().equalsIgnoreCase(label1In)) { 
            index = dList.indexOf(d);
            break;
         }    
      }
      if (index >= 0) {
         dList.get(index);
         result = dList.get(index);
      }
      return result;
   }

这是我尝试编译时遇到的错误。

DodecahedronListAppMenu.java:99: error: incompatible types: Dodecahedron cannot be converted to boolean
               if(myDList.findDodecahedron(label)) {

【问题讨论】:

    标签: java object if-statement arraylist boolean


    【解决方案1】:

    检查返回值是否为null。

    if (myDList.findDodecahedron(label) != null)
    

    您需要更新findDodecahedron() 以在未找到任何内容时返回 null,而不是新对象。更改result 的初始值会这样做:

    Dodecahedron result = null;
    

    或者,如果您在找到形状后立即返回形状,则可以摆脱 indexresult。无需保存其索引,然后在循环结束后查找索引。

    public Dodecahedron findDodecahedron(String label1In) {
       for (Dodecahedron d : dList) {
          if (d.getLabel().equalsIgnoreCase(label1In)) { 
             return d;
          }    
       }
       return null;
    }
    

    您还可以使用 Java 8 流进一步简化它:

    public Dodecahedron findDodecahedron(String label1In) {
       return dList.stream()
          .filter(d -> d.getLabel().equalsIgnoreCase(label1In))
          .findAny()
          .orElse(null);
    }
    

    【讨论】:

      【解决方案2】:

      如果您的方法不返回布尔值而是返回特定对象,则应将其分配给变量以利用它。 您不会实例化特定对象并将其返回以像布尔值一样对其进行测试。因此,您必须重复方法调用以再次检索结果,因为您需要在 std 输出中打印它。 这是无奈和重复的代码/处理。

      这应该看起来像:

      Dodecahedron obj = myDList.findDodecahedron(label)
      if(obj != null) {
          System.out.print(obj);
      }
      else {
          System.out.print("\t\"" + label + "\" not found");
      }
      

      【讨论】:

        【解决方案3】:

        您实际上是在此处实现null object design pattern。您可以在 findDodecahedron 方法中明确说明这一点(旁注 - 为了优雅,我用 Java 8 样式的流替换了实现,但这并不是真正必需的):

        public static final Dodecahedron NULL_DODECAHEDRON = new Dodecahedron("", "", 0);
        public Dodecahedron findDodecahedron(String label1In) {
              return dList.stream()
                          .filter(d -> d.getLabel().equalsIgnoreCase(label1In))
                          .findFirst()
                          .orElse(NULL_DODECAHEDRON);
        }
        

        然后在if条件中使用:

        if (!myDList.findDodecahedron(label).equals(NULL_DODECAHEDRON)) {
            System.out.print(myDList.findDodecahedron(label));
        } else {
            System.out.print("\t\"" + label + "\" not found");
        }
        

        【讨论】:

          【解决方案4】:

          首先,不要两次调用 find 方法。将结果分配给局部变量以供重复使用。

          多选:

          1. 由于您创建了一个带有空标签的 dummy 对象,如果找不到则返回该对象,您可以检查一下。

            Dodecahedron result = myDList.findDodecahedron(label);
            if (result.getLabel().isEmpty()) {
                System.out.print("\t\"" + label + "\" not found");
            } else {
                System.out.print(result);
            }
            

            替代方案是answer by Mureinik 中描述的null object design pattern

          2. 更改方法以返回 null 以表示未找到。

            public Dodecahedron findDodecahedron(String label1In) {
                for (Dodecahedron d : dList) {
                    if (d.getLabel().equalsIgnoreCase(label1In)) {
                        return d;
                    }
                }
                return null;
            }
            

            用途:

            Dodecahedron result = myDList.findDodecahedron(label);
            if (result != null) {
                System.out.print(result);
            } else {
                System.out.print("\t\"" + label + "\" not found");
            }
            
          3. 更改方法以返回 Optional (Java 8+)。

            public Optional<Dodecahedron> findDodecahedron(String label1In) {
                for (Dodecahedron d : dList) {
                    if (d.getLabel().equalsIgnoreCase(label1In)) {
                        return Optional.of(d);
                    }
                }
                return Optional.empty();
            }
            

            返回Optional 的替代方法是使用流。

            public Optional<Dodecahedron> findDodecahedron(String label1In) {
                return dList.stream()
                            .filter(d -> d.getLabel().equalsIgnoreCase(label1In))
                            .findFirst();
            }
            

            用途:

            Optional<Dodecahedron> result = myDList.findDodecahedron(label);
            if (result.isPresent()) {
                System.out.print(result.get());
            } else {
                System.out.print("\t\"" + label + "\" not found");
            }
            

          使用流的选项 3 是推荐的解决方案。

          【讨论】:

            猜你喜欢
            • 2013-12-02
            • 2019-05-22
            • 2010-09-13
            • 2012-12-06
            • 2019-07-24
            • 2013-03-07
            • 1970-01-01
            • 2021-10-01
            相关资源
            最近更新 更多