001/*
002 * Copyright (c) 2015-2020, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.util.infotheory.impl;
018
019import java.util.ArrayList;
020import java.util.Collections;
021import java.util.List;
022
023/**
024 * A row of values from a {@link RowList}.
025 * <p>
026 * Rows are defined with a hashcode and equals based on their contained values,
027 * and are immutable. They interact with the information theory calculations
028 * via the equals method.
029 * @param <T> The type of values.
030 */
031public final class Row<T> {
032    private final List<T> innerRow;
033
034    Row(List<T> innerRow) {
035        this.innerRow = Collections.unmodifiableList(new ArrayList<>(innerRow));
036    }   
037
038    @Override
039    public boolean equals(Object other) {
040        if (other instanceof Row) {
041            Row<?> otherRow = (Row<?>) other;
042            if (otherRow.innerRow.size() == innerRow.size()) {
043                boolean check = true;
044                for (int i = 0; i < innerRow.size(); i++) {
045                    check = check && innerRow.get(i).equals(otherRow.innerRow.get(i));
046                }
047                return check;
048            } else {
049                return false;
050            }
051        } else {
052            return false;
053        }
054    }
055
056    @Override
057    public int hashCode() {
058        int hash = 42;
059        for (T t : innerRow) {
060            hash ^= t.hashCode();
061        }
062        return hash;
063    }
064
065    @Override
066    public String toString() {
067        StringBuilder builder = new StringBuilder();
068        builder.append("Row = (");
069        for (T element : innerRow) {
070            builder.append(element.toString());
071            builder.append(',');
072        }
073        builder.deleteCharAt(builder.length()-1);
074        builder.append(')');
075        return builder.toString();
076    }
077}