From c6086a8752fa86ee4fb238a5c7b0ccff388a2233 Mon Sep 17 00:00:00 2001 From: Ben Culkin Date: Tue, 17 Nov 2020 20:04:03 -0500 Subject: Add static function for constructing IMap more easily Added a static function 'of' to IMap to allow you to more easily create a map from a list of key-value pairs. However, misuse of this method can result in getting ClassCastExceptions at some later point, because it has to use Object var-args + an unsafe generic cast. So, be careful, I suppose; and please make sure your argument types are correct. --- src/main/java/bjc/funcdata/IMap.java | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src') diff --git a/src/main/java/bjc/funcdata/IMap.java b/src/main/java/bjc/funcdata/IMap.java index 4906541..0879bca 100644 --- a/src/main/java/bjc/funcdata/IMap.java +++ b/src/main/java/bjc/funcdata/IMap.java @@ -201,4 +201,37 @@ public interface IMap extends IFreezable { return returns; } + + /** + * Static method to create a basic instance of IMap. + * + * @param The key type of the map. + * @param The value type of the map. + * + * @param args A series of key-value pairs. You will get an error if you don't + * provide the correct number of arguments (a number divisible by 2); + * however, if you pass arguments of the wrong type, you will not + * get a compile error, and usually won't get a runtime error in + * construction. However, you will get a ClassCastException as soon + * as you do something that attempts to iterate over the keys or values + * of the map. + * + * @return A map, constructed from the provided values. + * + * @throws IllegalArgumentException If you provide an incomplete pair of arguments. + */ + @SuppressWarnings("unchecked") + static IMap of(Object... args) { + if (args.length % 2 != 0) throw new IllegalArgumentException("Args must be in the form of key-value pairs"); + + IMap map = new FunctionalMap<>(); + for (int index = 0; index < args.length; index += 2) { + KeyType2 key = (KeyType2) args[index]; + ValueType2 value = (ValueType2) args[index + 1]; + + map.put(key, value); + } + + return map; + } } -- cgit v1.2.3