集合的操作
Posted by Bruce Tsai
狀況:Collection 中找出是否相同的物件
boolean hasMyOffer = false;
for(Offer offer : offerAll){
if(offer.getCode().equals(myOffer.getCode()) {
hasMyOffer = true;
}
}
正確做法:善用 api
- 使用 Collection.contains()
- 物件本身須實作 Object.equals() 與 Object.hashCode()
boolean hasMyOffer = offerAll.contains(myOffer);