Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
Varargs in Java are very handy and I've been using this feature quite a bit lately, but I did find some shortfalls that unfortunately mean I have to write some ugly code to get around the limitations.

To recap, there is an explanation of varargs here, but basically all this feature is, is a way to wrap an array of arguments to be passed to a method.

So in my server I can define a method like this:
public static void persist(final Object ... os) {
...
}


...and in the calling code use it like this:
persist(obj1, obj2, obj3);


Great so far, but what if I have a number of objects to persist plus an array of variable length that holds more objects to persist? I thought I could do this...
Object objarray[] = ...;
persist(obj1, obj2, obj3, objarray);


Unfortunately that doesn't work because java interprets that as a call to persist(Object[] a, Object[] b).

So how to get around it? Well the only way I could think of was to combine the varargs array and the other array I am passing in. This makes for some messy code before the persist() call so I'm open to other suggestions.



-i

Skip down to comments...
Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
 
comments powered by Disqus
Other posts you may like...