001 /*
002 * Java Genetic Algorithm Library (jenetics-5.1.0).
003 * Copyright (c) 2007-2019 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020 package io.jenetics.prog.op;
021
022 import java.math.BigDecimal;
023 import java.util.Objects;
024
025 /**
026 * This is the <em>sealed</em> base class for unmodifiable values. The only
027 * sub-classes of this type are {@link Const} and {@link EphemeralConst}.
028 *
029 * @see Const
030 * @see EphemeralConst
031 *
032 * @param <T> the type of the constant value
033 *
034 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
035 * @version 5.0
036 * @since 5.0
037 */
038 public abstract class Val<T> implements Op<T> {
039
040 private final String _name;
041
042 Val(final String name) {
043 _name = name;
044 }
045
046 @Override
047 public final String name() {
048 return _name;
049 }
050
051 /**
052 * Return the constant value.
053 *
054 * @return the constant value
055 */
056 public abstract T value();
057
058 /**
059 * The apply method will always returns the {@link #value()}.
060 *
061 * @param value the input parameters will be ignored
062 * @return always {@link #value()}
063 */
064 @Override
065 public final T apply(final T[] value) {
066 return value();
067 }
068
069 /**
070 * The arity of {@code Val} objects is always zero.
071 *
072 * @return always zero
073 */
074 @Override
075 public final int arity() {
076 return 0;
077 }
078
079 @Override
080 public final int hashCode() {
081 return Objects.hashCode(value());
082 }
083
084 @Override
085 public final boolean equals(final Object obj) {
086 return obj == this ||
087 obj instanceof Val &&
088 equals(((Val)obj).value(), value());
089 }
090
091 private static boolean equals(final Object a, final Object b) {
092 if (a instanceof Double && b instanceof Double) {
093 return ((Double)a).doubleValue() == ((Double)b).doubleValue();
094 } else if (a instanceof Float && b instanceof Float) {
095 return ((Float)a).floatValue() == ((Float)b).floatValue();
096 } else if (a instanceof BigDecimal && b instanceof BigDecimal) {
097 return ((BigDecimal)a).compareTo((BigDecimal)b) == 0;
098 }
099
100 return Objects.equals(a, b);
101 }
102
103 }
|