22
33# How to create non-empty arrays with var args
44
5- toc
5+ <!-- toc -->
6+ ## Contents
7+
8+ * [ The problem] ( #the-problem )
9+ * [ Runtime solution] ( #runtime-solution )
10+ * [ Compile time solution] ( #compile-time-solution )
11+ * [ Advantages] ( #advantages )
12+ * [ Where to use this] ( #where-to-use-this ) <!-- endToc -->
613
714## The problem
815
@@ -11,22 +18,47 @@ Most solutions for this occur at runtime. Of course, it would be better if they
1118
1219### Runtime solution
1320
14- snippet: minimalVarargsRuntime
21+ <!-- snippet: minimalVarargsRuntime -->
22+ <a id =' snippet-minimalvarargsruntime ' ></a >
23+ ``` java
24+ public Integer findSmallest(Integer . .. numbers)
25+ {
26+ if (numbers == null || numbers. length < 1 )
27+ { throw new IllegalArgumentException (" you must have at least one number" ); }
28+ // rest of the code
29+ ```
30+ < sup>< a href= ' /approvaltests-util-tests/src/test/java/com/spun/util/MinimumVarargSamples.java#L14-L20' title= ' Snippet source file' > snippet source< / a> | < a href= ' #snippet-minimalvarargsruntime' title= ' Start of snippet' > anchor< / a>< / sup>
31+ < ! -- endSnippet -- >
1532
1633### Compile time solution
1734
1835An easy way to deal with this is force the first parameter by declaring it explicitly.
1936If you do this , you will want to recombine this array almost immediately `ArrayUtils . combine(T , T . .. )` is an elegant way to do this .
2037Please be aware that it will not work with primitives.
2138
22- snippet: minimalVarargsCompileTime
39+ < ! -- snippet: minimalVarargsCompileTime -- >
40+ < a id= ' snippet-minimalvarargscompiletime' >< / a>
41+ ```java
42+ public Integer findSmallest(Integer first, Integer . .. numbers)
43+ {
44+ Integer [] combined = ArrayUtils . combine(first, numbers);
45+ // rest of the code
46+ ```
47+ < sup>< a href= ' /approvaltests-util-tests/src/test/java/com/spun/util/MinimumVarargSamples.java#L23-L28' title= ' Snippet source file' > snippet source< / a> | < a href= ' #snippet-minimalvarargscompiletime' title= ' Start of snippet' > anchor< / a>< / sup>
48+ < ! -- endSnippet -- >
2349
2450### Advantages
2551
2652If you use the runtime solution, the following will compile but throw an error when you run it.
2753If you use the compile time solution, it will not compile.
2854
29- snippet: minimalVarargsException
55+ < ! -- snippet: minimalVarargsException -- >
56+ < a id= ' snippet-minimalvarargsexception' >< / a>
57+ ```java
58+ int smallest = findSmallest();
59+ ```
60+ < sup>< a href= ' /approvaltests-util-tests/src/test/java/com/spun/util/MinimumVarargSamples.java#L10-L12' title= ' Snippet source file' > snippet source< / a> | < a href= ' #snippet-minimalvarargsexception' title= ' Start of snippet' > anchor< / a>< / sup>
61+ < ! -- endSnippet -- >
3062
3163### Where to use this
3264
0 commit comments