001/* 002 * Java Genetic Algorithm Library (jenetics-7.2.0). 003 * Copyright (c) 2007-2023 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 */ 020package io.jenetics.util; 021 022import static java.util.Objects.requireNonNull; 023 024import java.util.Comparator; 025import java.util.function.Supplier; 026 027/** 028 * Object wrapper, which makes the wrapped value {@link Comparable}, by defining 029 * a separate {@link Comparator}. 030 * 031 * @param <T> the type of the wrapped object 032 * 033 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 034 * @version 6.3 035 * @since 6.3 036 */ 037public final class Ordered<T> implements Comparable<Ordered<T>>, Supplier<T> { 038 private final T _value; 039 private final Comparator<? super T> _comparator; 040 041 private Ordered(final T value, final Comparator<? super T> comparator) { 042 _value = value; 043 _comparator = requireNonNull(comparator); 044 } 045 046 /** 047 * Return the wrapped value. 048 * 049 * @return the wrapped value 050 */ 051 @Override 052 public T get() { 053 return _value; 054 } 055 056 @Override 057 public int compareTo(final Ordered<T> other) { 058 return _comparator.compare(_value, other._value); 059 } 060 061 /** 062 * Make the given {@code value} comparable, by using the given 063 * {@code comparator}. 064 * 065 * @param value the wrapped object, may be {@code null} 066 * @param comparator the comparator used for comparing two value objects 067 * @param <T> the type of the wrapped object 068 * @return a new ordered object 069 * @throws NullPointerException if the given {@code comparator} is 070 * {@code null} 071 */ 072 public static <T> Ordered<T> of( 073 final T value, 074 final Comparator<? super T> comparator 075 ) { 076 return new Ordered<>(value, comparator); 077 } 078 079}