陣列的操作

Posted by Bruce Tsai

狀況:Array 中找出是否相同的物件

boolean hasMyOffer = false;
for(Offer offer : offerAll){
    if(offer.getCode().equals(myOffer.getCode()) {
        hasMyOffer = true;
    }
}

正確做法: 利用 Arrays.binarySearch()

boolean hasMyOffer = Arrays.binarySearch(offerAll, myOffer) > -1

狀況:陣列轉集合

Offer[] offers = fromResources();
List<Offer> offerList = new ArrayList<Offer>();
for (int i = 0; i < offers.length; i++) {
    offerList.add(offers[i]);
}

正確做法:利用 Arrays.asList()

Offer[] offers = fromResources();
List<Offer> offerList = Arrays.asList(offers);

results matching ""

    No results matching ""