Networks: Replace usage of Guava ImmutableSet with Collections.unmodifiableSet().

This commit is contained in:
Sean Gilligan 2020-05-26 13:19:07 -07:00 committed by Andreas Schildbach
parent f6c8b0dbe3
commit 8deb113a5e

View file

@ -17,10 +17,11 @@
package org.bitcoinj.params;
import org.bitcoinj.core.NetworkParameters;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
@ -32,7 +33,7 @@ import java.util.Set;
*/
public class Networks {
/** Registered networks */
private static Set<NetworkParameters> networks = ImmutableSet.<NetworkParameters>of(TestNet3Params.get(), MainNetParams.get());
private static Set<NetworkParameters> networks = unmodifiableSet(TestNet3Params.get(), MainNetParams.get());
public static Set<NetworkParameters> get() {
return networks;
@ -44,7 +45,7 @@ public class Networks {
* @param network Network to register/add.
*/
public static void register(NetworkParameters network) {
register(Lists.newArrayList(network));
register(Collections.singleton(network));
}
/**
@ -53,11 +54,8 @@ public class Networks {
*
* @param networks Networks to register/add.
*/
public static void register(Collection<? extends NetworkParameters> networks) {
ImmutableSet.Builder<NetworkParameters> builder = ImmutableSet.builder();
builder.addAll(Networks.networks);
builder.addAll(networks);
Networks.networks = builder.build();
public static void register(Collection<NetworkParameters> networks) {
Networks.networks = combinedSet(Networks.networks, networks);
}
/**
@ -66,14 +64,25 @@ public class Networks {
* @param network Network type to unregister/remove.
*/
public static void unregister(NetworkParameters network) {
if (networks.contains(network)) {
ImmutableSet.Builder<NetworkParameters> builder = ImmutableSet.builder();
for (NetworkParameters parameters : networks) {
if (parameters.equals(network))
continue;
builder.add(parameters);
}
networks = builder.build();
}
Networks.networks = removeFromSet(networks, network);
}
// Create an unmodifiable set of NetworkParameters from an array/varargs
private static Set<NetworkParameters> unmodifiableSet(NetworkParameters... ts) {
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ts)));
}
// Create an unmodifiable set by combining two collections
private static <T> Set<T> combinedSet(Collection<T> a, Collection<T> b) {
Set<T> tempSet = new HashSet<>(a);
tempSet.addAll(b);
return Collections.unmodifiableSet(tempSet);
}
// Create a new unmodifiable set by removing an item from an existing set
private static <T> Set<T> removeFromSet(Set<T> set, T item) {
Set<T> tempSet = new HashSet<>(set);
tempSet.remove(item);
return Collections.unmodifiableSet(tempSet);
}
}