2017-02-14 54 views
0

我的目標是要求用戶輸入名字和姓氏,然後將其轉換爲自定義的FullName類,然後搜索HashMap以找到具有相同名字和姓氏的鍵並返回值。由於某些原因,每當我運行代碼並把名稱放在空的時候。HashMaps難點

package hw4; 

import java.io.*; 
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.Set; 

public class Test2 { 

public static void main(String[] args) throws FileNotFoundException, IOException { 
    HashMap<FullName, Integer> map = new HashMap<>(); 

    FullName n = new FullName("John", "Smith"); 
    map.put(n, 1); 

    String f, l; 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.print("First: "); 
    f = in.readLine(); 
    System.out.print("Last: "); 
    l = in.readLine(); 
    FullName fl = new FullName(f, l); 
    System.out.print(map.get(fl)); 
    } 
} 

這裏是FullName類。

public class FullName 
{ 
private final String firstName; 
private final String lastName; 

public FullName(String first, String last) { 
    firstName = first; 
    lastName = last; 
} 

public String getFirstName() { return firstName; } 
public String getLastName() { return lastName; } 

public boolean equals(FullName otherName) 
{ 
    if (firstName == otherName.firstName && lastName == otherName.lastName) 
    {return true;} 

    return false; 
    } 
} 
+0

請編輯您的文章以包含'FullName'類定義。 –

+4

你在'FullName'類中實現了'equals()'和'hashCode()'嗎? –

+0

當您比較'Strings'的等同性時,您需要使用'equals()'而不是'=='。另外,您必須調用getFirstName()和getLastName()方法,而不是使用點運算符(即otherName.firstName)。 – Ares

回答

0

你還沒有真的重寫equals方法。因爲equals將Object作爲參數。另外,使用equals來比較不是==的對象。 ==比較參考變量。

import java.io.*; 
import java.util.HashMap; 
import java.util.HashSet; 
import java.util.Set; 

public class Test2 { 

    public static void main(String[] args) throws FileNotFoundException, IOException { 
     HashMap<FullName, Integer> map = new HashMap<>(); 

     FullName n = new FullName("John", "Smith"); 
     map.put(n, 1); 
     System.out.println(n.hashCode()); 

     String f, l; 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     f = in.readLine(); 
     l = in.readLine(); 
     FullName fl = new FullName(f, l); 
     System.out.println(fl.hashCode()); 

      System.out.print(map.containsKey(fl)); 
    } 
} 

class FullName { 
    private final String firstName; 
    private final String lastName; 

    public FullName(String first, String last) { 
     firstName = first; 
     lastName = last; 
    } 

    public String getFirstName() { 
     return firstName; 
    } 

    public String getLastName() { 
     return lastName; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     FullName otherName = (FullName) obj; 

     if (getFirstName().equals(otherName.getFirstName()) && getLastName().equals(otherName.getLastName())) { 
      return true; 
     }  
     return false; 
    } 



    @Override 
    public int hashCode() { 

     return firstName.length()+lastName.length(); 
    } 
}