2016-11-11 4 views
2

Iveはこれで2時間座っていましたが、解決策が見つかりません。電話がnullの場合、リストに追加する代わりにgetFriend()メソッドから例外がキャストされるため、複数のFriendをArrayListに追加することはできません。これを回避する簡単な方法は何ですか?Java addメソッドが例外と矛盾しています

/** 
* Ensures you can only add a friend if a friend with same phone number doesn't exist 
* @param f as Friend 
* @return boolean 
*/ 

public boolean addFriend(Friend f){ 
    if(getFriend(f.getPhone()) == null) { 
     friends.add(f); 
     return true; 
    } 
    else { 
     System.out.println("-------------------------------------"); 
     System.out.println("Member with that phone already exists"); 
     System.out.println("-------------------------------------"); 
     return false; 
    } 
} 


/** 
* Searches the arraylist for a friend matching phone 
* 
* @param phone as String 
* @return Friend if matching phone, else returns a null 
*/ 
public Friend getFriend(String phone) { 
    Friend res = null; 
    if(friends.size() != 0){ 
     for(Friend f : friends) { 
      if(f.getPhone().equals(phone)){ 
       res = f; 
      } 
     } 
     if(res == null){ 
      throw new NullPointerException("No result found"); 
     } 
    } 
    return res;  
} 

答えて

2

単にnullを返すように変更

if(res == null){ 
     throw new NullPointerException("No result found"); 
} 

nullを確認しているので安全です。そのことについて

public Friend getFriend(String phone) { 
if(friends.size() != 0){ 
    for(Friend f : friends) { 
     if(f.getPhone().equals(phone)){ 
      return f; 
     } 
    } 
} 
return null;  
} 
0
if(res == null && friends.size() == 0){ 

どのように?それは有効な解決策ですか?

+0

いいえ。全体の 'アーキテクチャ'を変更するScary Wombatsソリューションをお勧めします。例外を取り除くため。 –

+0

ありがとうございました! –

+0

お歓迎します。 arraylistにはbooleanを返す空の有無を調べるisEmpty()メソッドがあります。 http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty-- –

関連する問題