Is there any method to build a varargs array in Java?

There is a very useful Arrays.asList() :

 public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); } 

But no Arrays.array() :

 public static <T> T[] array(T... values) { return values; } 

Being completely trivial, this would be a convenient way to build arrays:

 String[] strings1 = array("1", "1", "2", "3", "5", "8"); // as opposed to the slightly more verbose String[] strings2 = new String[] { "1", "1", "2", "3", "5", "8" }; // Of course, you can assign array literals like this String[] strings3 = { "1", "1", "2", "3", "5", "8" }; // But you can't pass array literals to methods: void x(String[] args); // doesn't work x({ "1", "1", "2", "3", "5", "8" }); // this would x(array("1", "1", "2", "3", "5", "8")); 

Is there such a method somewhere else in the Java language, outside of java.util.Arrays ?

+4
source share
4 answers

You can see ArrayUtils from Apache Commons , you should use lib version 3.0 or higher.

Examples:

 String[] array = ArrayUtils.toArray("1", "2"); String[] emptyArray = ArrayUtils.<String>toArray(); 
+3
source

In my opinion, in Java there is no need for the array() method. If you want less details, as you said, you can use literals. Or you can use varargs in the method parameters (there is no need for an array at all). Based on your title, this is what you want to do. You can simply do this:

 public static void doThings(String... values) { System.out.println(values[0]); } doThings("This", "needs", "no", "array"); 

Only if the method signature actually has an array, you will need to specify new String[] , which, in my opinion, is not too much additional writing.

Edit: It seems that you need a less accurate way to call methods with arrays as parameters. I would not add an external library from just a single line method. This will work, for example:

 public static <T> T[] toArr(T... values) { return values; } yourMethod(toArr("1", "2", "3")); 
+1
source

ArrayUtils from Apache Commons Lang (v3.0 or later):

 String[] array = ArrayUtils.toArray("1", "2"); String[] emptyArray = ArrayUtils.<String>toArray(); 

... or just take the code from Apache and implement it "yourself":

 public static <T> T[] toArray(final T... items) { return items; } 
+1
source

If you want something shorter

 x(new String[] {"1", "1", "2", "3", "5", "8"}); 

I use the following, which is smaller than the list itself.

  x("1,1,2,3,5,8".split(",")); // {"1", "1", "2", "3", "5", "8"} 

It does not use any additional library.


Say you need keys and values ​​that you can use varargs anyway

 public static <K,V> Map<K, V> asMap(K k, V v, Object ... keysAndValues) { Map<K,V> map = new LinkedHashMap<K, V>(); map.put(k, v); for(int i=0;i<keysAndValues.length;i+=2) map.put((K) keysAndValues[i], (V) keysAndValues[i+1]); return map; } 
+1
source

Source: https://habr.com/ru/post/1381269/


All Articles