2
2
3
3
# How to create non-empty arrays with var args
4
4
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 -->
6
13
7
14
## The problem
8
15
@@ -11,22 +18,47 @@ Most solutions for this occur at runtime. Of course, it would be better if they
11
18
12
19
### Runtime solution
13
20
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 -- >
15
32
16
33
### Compile time solution
17
34
18
35
An easy way to deal with this is force the first parameter by declaring it explicitly.
19
36
If you do this , you will want to recombine this array almost immediately `ArrayUtils . combine(T , T . .. )` is an elegant way to do this .
20
37
Please be aware that it will not work with primitives.
21
38
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 -- >
23
49
24
50
### Advantages
25
51
26
52
If you use the runtime solution, the following will compile but throw an error when you run it.
27
53
If you use the compile time solution, it will not compile.
28
54
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 -- >
30
62
31
63
### Where to use this
32
64
0 commit comments