001 /*
002 * Java GPX Library (jpx-3.1.0).
003 * Copyright (c) 2016-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 */
020 package io.jenetics.jpx;
021
022 import static java.util.Objects.requireNonNull;
023
024 import java.util.Collection;
025 import java.util.HashSet;
026 import java.util.Iterator;
027 import java.util.List;
028 import java.util.Objects;
029 import java.util.Set;
030
031 /**
032 * Helper methods for handling lists. All method handles null values correctly.
033 *
034 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
035 * @version 2.0
036 * @since 1.0
037 */
038 final class Lists {
039
040 private Lists() {
041 }
042
043 static <T> List<T> copyOf(final List<? extends T> list) {
044 return list == null ? List.of() : List.copyOf(list);
045 }
046
047 static <T> void copyTo(
048 final List<? extends T> source,
049 final List<? super T> target
050 ) {
051 requireNonNull(target);
052 if (source != null) {
053 source.forEach(Objects::requireNonNull);
054 }
055
056 target.clear();
057 if (source != null) {
058 target.addAll(source);
059 }
060 }
061
062 static int hashCode(final List<?> list) {
063 return list != null
064 ? 17*list.stream().mapToInt(Objects::hashCode).sum() + 31
065 : 0;
066 }
067
068 static boolean equals(final List<?> b, final List<?> a) {
069 boolean result = false;
070 if (a != null) {
071 if (b != null) {
072 result = a.size() == b.size();
073 if (result) {
074 result = a.isEmpty()|| containsAll(a, b);
075 }
076 }
077 } else {
078 result = b == null;
079 }
080
081 return result;
082 }
083
084 private static boolean containsAll(final Collection<?> a, final Collection<?> b) {
085 final Iterator<?> ita = a.iterator();
086 final Set<Object> visited = new HashSet<>();
087
088 for (final Object next : b) {
089 if (visited.contains(next)) {
090 continue;
091 }
092
093 boolean foundCurrentElement = false;
094 while (ita.hasNext()) {
095 final Object p = ita.next();
096 visited.add(p);
097
098 if (Objects.equals(next, p)) {
099 foundCurrentElement = true;
100 break;
101 }
102 }
103
104 if (!foundCurrentElement) {
105 return false;
106 }
107 }
108
109 return true;
110 }
111
112 }
|