Operation.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-7.1.0).
03  * Copyright (c) 2007-2022 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19  */
20 package io.jenetics.prog.op;
21 
22 import static java.util.Objects.requireNonNull;
23 import static io.jenetics.internal.util.Hashes.hash;
24 
25 import java.io.Serial;
26 import java.io.Serializable;
27 import java.util.Objects;
28 import java.util.function.Function;
29 
30 /**
31  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
32  @version 4.1
33  @since 3.9
34  */
35 final class Operation<T> implements Op<T>, Serializable {
36 
37     @Serial
38     private static final long serialVersionUID = 1L;
39 
40     private final String _name;
41     private final int _arity;
42     private final Function<T[], T> _function;
43 
44     Operation(
45         final String name,
46         final int arity,
47         final Function<T[], T> function
48     ) {
49         _name = requireNonNull(name);
50         _function = requireNonNull(function);
51         if (arity < 0) {
52             throw new IllegalArgumentException(
53                 "Arity smaller than zero: " + arity
54             );
55         }
56 
57         _arity = arity;
58     }
59 
60     @Override
61     public String name() {
62         return _name;
63     }
64 
65     @Override
66     public int arity() {
67         return _arity;
68     }
69 
70     @Override
71     public T apply(final T[] values) {
72         return _function.apply(values);
73     }
74 
75     @Override
76     public int hashCode() {
77         return hash(_name, hash(_arity));
78     }
79 
80     @Override
81     public boolean equals(final Object obj) {
82         return obj == this ||
83             obj instanceof Operation<?> other &&
84             Objects.equals(other._name, _name&&
85             other._arity == _arity;
86     }
87 
88     @Override
89     public String toString() {
90         return _name;
91     }
92 
93 }