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;
}
いいえ。全体の 'アーキテクチャ'を変更するScary Wombatsソリューションをお勧めします。例外を取り除くため。 –
ありがとうございました! –
お歓迎します。 arraylistにはbooleanを返す空の有無を調べるisEmpty()メソッドがあります。 http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty-- –