Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Although Java as a compilation language, but it also provides a lot of runtime capabilities, today introduces a very basic knowledge, variable parameter passing
Creating a Map object is quite common in daily development. Now I want to write a utility class that makes it very easy to create and initialize a Map object
So we can implement a MapUtil utility class to support this scenario
public static <K, V> Map<K, V> newMap(K k, V v, Object... kv) {
Map<K, V> ans = new HashMap<>();
ans.put(k, v);
for (int i = 0; i < kv.length; i += 2) {
ans.put((K) kv[i], (V) kv[1]);
}
return ans;
}
Copy the code
Note that kv is the variable argument we are talking about. Inside the method, kv can be treated as an array object (and a safe object, not null when not passed).
Here are some things to be aware of when using mutable parameters
Variable arguments conflict with array arguments
Note that the following two methods do not occur at the same time, and directly cause a compilation error
public static <K, V> Map<K, V> newMap(K k, V v, Object... kv)
public static <K, V> Map<K, V> newMap(K k, V v, Object[] kv)
Copy the code
Overload selection
If the method has only one variable argument, newMap(“key”, “value”) will not give an error and will directly access the following method, with kv as an empty array
public static <K, V> Map<K, V> newMap(K k, V v, Object... kv)
Copy the code
When an overload occurs, it is as follows
public static <K, V> Map<K, V> newMap(K k, V v, Object... kv)
public static <K, V> Map<K, V> newMap(K k, V v)
Copy the code
Which of the above two methods will be called if only two parameters are passed?
newMap("key", "value")
The following method is called- Above method called by ‘newMap(“key”, “value”, “k”, “v”)
What happens when you pass a variable argument to an array
Although we use it as an array, is it possible to pass it as an array?
public static <K, V> Map<K, V> newMap(K k, V v, Object... kv) {
Map<K, V> ans = new HashMap<>();
ans.put(k, v);
for (int i = 0; i < kv.length; i += 2) {
ans.put((K) kv[i], (V) kv[1]);
}
return ans;
}
@Test
public void tt(a) {
Map map = newMap("key"."value".new Object[]{"1"."2"});
System.out.println(map);
}
Copy the code
The actual output is as follows
{1=2, key=value}
Copy the code
From a practical test, passing arrays is fine
II. The other
1. A gray Blog:liuyueyi.github.io/hexblog
A gray personal blog, recording all the study and work in the blog, welcome everyone to go to stroll
2. Statement
As far as the letter is not as good, the above content is purely one’s opinion, due to the limited personal ability, it is inevitable that there are omissions and mistakes, if you find bugs or have better suggestions, welcome criticism and correction, don’t hesitate to appreciate
- Micro Blog address: Small Gray Blog
- QQ: a gray /3302797840
- Wechat official account: One Grey Blog