summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Culkin <scorpress@gmail.com>2020-11-17 20:04:03 -0500
committerBen Culkin <scorpress@gmail.com>2020-11-17 20:04:03 -0500
commitc6086a8752fa86ee4fb238a5c7b0ccff388a2233 (patch)
tree34ef1ebced4d2be48e627f814eb6cd9022cc2356
parent41e2c9e80b18620aaa9a23f759064bf058ad980e (diff)
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.
-rw-r--r--src/main/java/bjc/funcdata/IMap.java33
1 files changed, 33 insertions, 0 deletions
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<KeyType, ValueType> extends IFreezable {
return returns;
}
+
+ /**
+ * Static method to create a basic instance of IMap.
+ *
+ * @param <KeyType2> The key type of the map.
+ * @param <ValueType2> 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 <KeyType2, ValueType2> IMap<KeyType2, ValueType2> of(Object... args) {
+ if (args.length % 2 != 0) throw new IllegalArgumentException("Args must be in the form of key-value pairs");
+
+ IMap<KeyType2, ValueType2> 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;
+ }
}