private List list(int... ints) {
		List result = new ArrayList();
		
		for (int i : ints) {
			result.add(i);
		}
		
		return result;
	}

I got this method from one of my friends and wondered what it does?
I have never seen int... ints construct before but am assuming it is an array of int and uses a for each construct to add each int in the array to result and return that List. Could someone pleas explain to me what the int... ints parameters mean, what they are doing, how to do that with other types, and if there are any advantages over int[] (if the paramter is just an array of int like I am guessing)?

Recommended Answers

All 5 Replies

There is no such thing as an "int... ints" construct. Besides which, your friends coding is poor. ArrayList shouldn't be used as a raw type like that, specify the type (an example:)

ArrayList<Integer> list = new ArrayList<Integer>();

using raw types can be required at times, but this is not such a time.
All answers can be found in a decent tutorial and the JLS as usual.

It is legal code. It is used to generate a list in JUnit 4 Test Class. For example, list(2, 3) returns [2, 3]. I was wondering if anyone knew the formalities of the parameters since I couldn't find them on the java sun site. I was thinking it just creates a list of int out of the arguments you pass it and puts them into an int[] called ints. For example, list(2, 3) would put 2 and 3 into an array of int of size 2 with ints[0] = 2 and ints[1] = 3. If anyone knows or can find the documentation please help me on this one.

Yeah I know it is legal code. S.o.S posted a good article on type erasure a month or so ago. As jwenting indirectly pointed out, being legal doesn't make it a good idea.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.