aboutsummaryrefslogtreecommitdiffstats
path: root/predicate-search-core/src/main/java/com/yahoo/document/predicate/Conjunction.java
blob: a5b190d95ab902a9d39e70156f7d84d392e0e896 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * @author Simon Thoresen Hult
 */
public class Conjunction extends PredicateOperator {

    private List<Predicate> operands;

    public Conjunction(Predicate... operands) {
        this(Arrays.asList(operands));
    }

    public Conjunction(List<? extends Predicate> operands) {
        this.operands = new ArrayList<>(operands);
    }

    public Conjunction addOperand(Predicate operand) {
        operands.add(operand);
        return this;
    }

    public Conjunction addOperands(Collection<? extends Predicate> operands) {
        this.operands.addAll(operands);
        return this;
    }

    public Conjunction setOperands(Collection<? extends Predicate> operands) {
        this.operands.clear();
        this.operands.addAll(operands);
        return this;
    }

    @Override
    public List<Predicate> getOperands() {
        return operands;
    }

    @Override
    public Conjunction clone() throws CloneNotSupportedException {
        Conjunction obj = (Conjunction)super.clone();
        obj.operands = new ArrayList<>(operands.size());
        for (Predicate operand : operands) {
            obj.operands.add(operand.clone());
        }
        return obj;
    }

    @Override
    public int hashCode() {
        return operands.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Conjunction)) {
            return false;
        }
        Conjunction rhs = (Conjunction)obj;
        if (!operands.equals(rhs.operands)) {
            return false;
        }
        return true;
    }

    @Override
    protected void appendTo(StringBuilder out) {
        for (Iterator<Predicate> it = operands.iterator(); it.hasNext(); ) {
            Predicate operand = it.next();
            if (operand instanceof Disjunction || operand instanceof FeatureConjunction) {
                out.append('(');
                operand.appendTo(out);
                out.append(')');
            } else {
                operand.appendTo(out);
            }
            if (it.hasNext()) {
                out.append(" and ");
            }
        }
    }

}