如何比较从初始arraylist到多个arraylists的对象,直到它返回true?

时间:2016-10-20 00:38:58

标签: java arraylist

    public  boolean makeSuggestion(ArrayList<Cards> firstPlayerCards,ArrayList<Cards> secondPlayerCards){
    Iterator<Cards> p1Iterator = firstPlayerCards.iterator();
    while (p1Iterator.hasNext()) {
        Iterator<Cards> p2Iterator = secondPlayerCards.iterator();
        while(p2Iterator.hasNext()) {
            Cards p1card = p1Iterator.next();
            Cards p2card = p2Iterator.next();
            if (p1card.equals(p2card)) {
                return false;
            }
        }
    }
    return true;
}

}

这是我到目前为止所拥有的。我想将第一个arraylist(firstPlayerCards)的对象与其他arraylist的对象进行比较,直到它找到一个等于它的对象。然后它将返回true并停止该方法。

2 个答案:

答案 0 :(得分:0)

public  boolean makeSuggestion(ArrayList<Cards>firstPlayerCards, ArrayList<ArrayList<Cards>> compareLists){

    //For each card in first list
    for(Cards first: firstPlayerCard){

        //For each list you wish to compare against
        for(ArrayList<Cards> secondPlayerCards: compareLists){

            //For each card in the list compare against first list
            for(Cards second: secondPlayerCards){
                if(first.equals(second)) return true;
            }
        }
    }
}

这会遍历第一张卡片列表,对于每张卡片,它会遍历第二个列表并比较每个对象,如果它们相等则返回true。

答案 1 :(得分:0)

public  boolean makeSuggestion(ArrayList<Cards> firstPlayerCards,ArrayList<Cards> secondPlayerCards){
    for(Card firstPlayerCard:firstPlayerCards){
        for(Card secondPlayerCard:secondPlayerCards){
            if(firstPlayerCard.equals(secondPlayerCard)){
                return true;
            }
        }
    }
    return false;
}