【问题标题】:How can i fix this method我该如何解决这个方法
【发布时间】:2016-08-26 18:18:00
【问题描述】:

我希望有人帮助我重写此方法,使其能够在无法找到匹配项时找到匹配项

public boolean equals(Object otherObject)    {
      if (otherObject ==null)
      {
         return false;
      }
      else if (getClass() != otherObject.getClass())
      {
         return false;
      }
      else
      {
         Contact otherContact = (Contact)otherObject;
         return (first.equals(otherContact.first) && 
               last.equals(otherContact.last)&&
               phone.equals(otherContact.phone)&&
               email.equals(otherContact.email));
      }    }

它显示我的输入中有匹配项时没有匹配项

public void displayMatch()
{

    System.out.println("Enter keyword: ");
    Scanner input = new Scanner(System.in);
    String in = input.next();

        for (Contact c : contacts)
        {
            if (in.equals(c)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }   
}

【问题讨论】:

  • 您试图将 String 与 Contact 进行比较,这对我来说没有意义。
  • 带关键字的数组列表内容
  • 这个“关键字”代表什么?

标签: java arraylist methods


【解决方案1】:

由于您将字符串与对象进行比较,因此它不起作用。你需要比较两个对象。

所以你要做的就是询问用户的输入,创建Contact 对象并调用equals。见下文

    public void displayMatch() {

        System.out.println("Enter keyword: ");
        Scanner input = new Scanner(System.in);
        String firstName = input.nextLine();
        String lastName = input.nextLine();
        String phone = input.nextLine();
        String email = input.nextLine();

        Contact inputContact = new Contact(firstName, lastName, phone, email);


        for (Contact c : contacts) {
            if (c.equals(inputContact)) {
                System.out.println(c);
            } else {
                System.out.println("No matches.");
            }
        }
    }

【讨论】:

  • 还应该建议他们在他们的Contact类上实现@Override equals()方法和@Override hashcode()
  • @Draken 同意。无论何时使用 Collection,equals 和 hashcode 都应该被覆盖。
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多