aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/main/java/com/yahoo/document/datatypes/CollectionFieldValue.java
blob: 63f4ea44de1ad99ae8ce9e7d8453982a4fc6e73f (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.datatypes;

import com.yahoo.document.CollectionDataType;

import java.util.Collection;
import java.util.Iterator;

/**
 * Superclass of multivalue field values
 *
 * @author Håkon Humberset
 */
public abstract class CollectionFieldValue<T extends FieldValue> extends CompositeFieldValue {

    CollectionFieldValue(CollectionDataType type) {
        super(type);
    }

    @Override
    public CollectionDataType getDataType() {
        return (CollectionDataType) super.getDataType();
    }

    /**
     * Utility function to wrap primitives.
     *
     * @see Array.ListWrapper
     */
    protected FieldValue createFieldValue(Object o) {
        if (o instanceof FieldValue) {
            if (!getDataType().getNestedType().isValueCompatible((FieldValue) o)) {
                throw new IllegalArgumentException(
                        "Incompatible data types. Got "
                                + ((FieldValue)o).getDataType() + ", expected "
                                + getDataType().getNestedType());
            }
            return (FieldValue) o;
        } else {
            FieldValue fval = getDataType().getNestedType().createFieldValue();
            fval.assign(o);
            return fval;
        }
    }

    public void verifyElementCompatibility(T o) {
        if (!getDataType().getNestedType().isValueCompatible(o)) {
            throw new IllegalArgumentException(
                    "Incompatible data types. Got "
                    + o.getDataType() + ", expected "
                    + getDataType().getNestedType());
        }
    }

    public abstract Iterator<T> fieldValueIterator();

    // Collection implementation

    public abstract boolean add(T value);

    public abstract boolean contains(Object o);

    public abstract boolean isEmpty();

    protected boolean isEmpty(Collection collection) {
        return collection.isEmpty();
    }

    public abstract Iterator<T> iterator();

    public abstract boolean removeValue(FieldValue o);

    protected boolean removeValue(FieldValue o, Collection collection) {
        int removedCount = 0;
        while (collection.remove(o)) {
            ++removedCount;
        }
        return (removedCount > 0);
    }

    public abstract int size();

}