What does int[]... arrays mean in Java? - java

Can you help me? What does int[]... arrays mean in Java?
Example:
public static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}

That is called varargs.. notation,
So that you can pass individual int[] objects to that method,, without worrying of no.of arguments.
When you write
public static int[] concat(int[]... arrays) {
Now you can use that method like
Classname.concat(array1,array2,array3) //example1
Classname.concat(array1,array2) //example2
Classname.concat(array1,array2,array3,array4) //example3
A clear benefit is you need not to prepare an array to pass a method. You can pass values of that array directly.

It means that the concat function can receive zero or more arrays of integers (int[]). That's why you can loop over the arrays argument, accessing one of the arrays contained in each iteration - if any. This is called variable arguments (or varargs).
Check this other question for more info.

This means, that you can pass zero, one or more arrays of int (int[]) to your method. Consider following example
public void method(String ... strings)
can be called as
method()
method("s")
method("s", "d")
...
So your method can be called as
concat()
concat(new int[0])
concat(new int[0], new int[0])
...

This means that you can pass the method any number of int[] objects:
concat(new int[]{1,2});
concat(new int[]{1,2}, new int[]{3,4,5});
concat(new int[]{1}, new int[]{3,4,5,6}, new int[]{1,1,1,1,1,1,1});
Why this is useful? It's clear why :)

The ... is the most important part, it means you can have an unlimited amount of integers passed in and it is just accessed via the array, so you could call it as:
concat(1,2,3,4,5) or concat(1)
Most languages have this sort of feature, some call it var args others call it params.

varargs ("...") notation basically informs that the arguments may be passed as a sequence of arguments (here - ints) or as an array of arguments. In your case, as your argument is of type "array of int", it means arguments may be passed as a sequence of arrays or as an array of arrays of int (note that array of arrays is quite equivalent to multidimensional array in Java).

For example you have a method:
void functionName (Object objects...)
{
Object object1=objects[0];
Object object2=objects[1];
Object object3=objects[2];
}
You can use your method as:
Object object1,object2,object3;
functionName(object1,object2,object3);

Using Variable Arguments
The ellipsis (...) identifies a variable number of arguments, and
is demonstrated in the following summation method.
public static int[] concat(int[]... arrays)
Use method
concat(val1, val2, val3);
concat(val1, val2, val3, val3);

Related

Semantics of returning arrays

When I create a method to determine what value I want to return, usually I can return a value directly - like so:
return 0;
However, I've discovered that when returning arrays, I have to create a new instance of an array, and return it - like so:
String[] rtnArr = {"str1", "str2"};
return rtnArr;
Why is this? Am I creating two arrays here, or am I only specifying a type when I instantiate the method?
Edit: I should clarify that I am returning one or another array based on a preliminary condition. That is to say, I have a switch and each case returns an array of different strings.
You are not creating two arrays. Array initializers are only allowed when initiating a variable, so you can't use them directly in a return statement.
You don't actually need a variable to return an array. You can also return an array like this
return new String[] {"Hello", "World"};
When you declare an array you can initialize it as String test[] = {"Hello", "World"}; because the array is obviously a string array so you don't need to do new String[] {"Hello", "World"}, but otherwise, you need an explicit initialization of the array with a type for type safety.
I've discovered that when returning arrays, I have to create a new instance of an array, and return it Why is this ? Am I creating two arrays here, or am I only specifying a
type when I instantiate the method ?
You don't need to return a new instance of the array always, sometimes you might need to return an existing array object as shown in the below code:
public class MyArrayTest {
private String[] myArray;
public MyArrayTest(String[] myArray) {
this.myArray = myArray;
}
public String[] getMyArray() {
return myArray;//returning existing array object
}
}

How do I make a method accept different parameter datatypes in java?

I found the code below from this SO question. It has worked great so far, but I have come across the need to shuffle arrays of strings. The code below only accepts arrays of ints as a parameter. I am still very new to java and I can't seem to figure out how to let the method accept multiple datatypes in it's parameters. It would be wonderful if I could use the same method to shuffle arrays of ints AND arrays of strings. Can anyone help?
static int[] shuffle(int[] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
You should have different methods for different parameters. This will be method overloading.
In your case (for strings and int)
static int[] shuffle(int[] array)
static String[] shuffle(String[] array)
Or you can have Object array in argument of your method. That way you have to define your int array as Integer class array in calling method.
static Object[] shuffle(Object[] array)
Object is the superclass of all classes in Java and subclass' object can be handled by superclass' reference.
Since int is primitive type, not a class, you have to define int array as Integer array. Integer is type wrapper class for int.
You can have two different methods. One that shuffles arrays of ints and one that shuffles arrays of strings.
static String[] shuffleStringArray(String[] ar){
//method logic goes here
}
The basic structure of your method shouldn't change too much.
Good luck!
Java solves this problem by making arrays covarient. This means that if B is a subtype of A the B[] is a subtype of A[]. This means that you can make you parameter type Object[] and you can pass in any array of object. For primitive types like int you still need to write a separate method however because primitives are not objects.
Use a generic array this way
static <T> T[] shuffle(T[] ar){
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
T a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
Invoke it like so:
System.out.println(Arrays.toString(shuffle(new Integer[]{1,2,3,4})));
(or)
System.out.println(Arrays.toString(shuffle(new String[]{"a","b","c"})));
You cannot do that if you need to support both objects and primitives. You need to create an overloaded method for each primitive type and one for Object. Each version of this method will re-implement the same algorithm with diferent data types.
Your method is analogous to the ones in java.util.Arrays class. Take a look at Arrays.java source code from Open JDK.
http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/be44bff34df4/src/share/classes/java/util/Arrays.java
You can't have a method perform the same operations on an int array and a reference type array, because Java treats those as completely different types, and their common superclass (Object) lacks functionality as an array. However, you seem to be getting at overloading (see Overloading Methods part). You can have a seperate implementation of the method for different parameters. Simply copy/paste your code and replace relevant instances of int with String. This is actually what is done for the primitive type arrays in Arrays.copyOf.

What are Strings... objects called as?

I didn't know what to look for so i couldn't google this one but..
What are String... parameters called as ?
And how do you get individual strings when more than one String object is passed through a String... object ?
A String... is syntactic sugar for an String[] and you access the values of the String array just like any other String array. In fact you can write this simple method.
public static <T> T[] asArray(T... ts) {
return ts;
}
This takes a vararg array can returns an array.
The key difference is that you can write
asArray(1, 2, 3); // much shorter.
instead of having to write
asArray(new Integer[] { 1, 2, 3 });
this is a feature introduced with jdk 1.5. basically the last parameter of a method can be declared as ... and that means
from method caller pespective you can pass zero, one or many instances of that type
within method the .... param is basically seen as an array

array-element:array-name in Java

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

why arrays of primitive types are not considered as objects

I know that arrays in java extends Objects,So why passing them as params doesn't work.
public static void main(String[] args) {
foo(new Integer[]{1, 2, 3}); // 1
foo(new int[]{1,2,3}); //2
}
static void foo(Object... params) {
System.out.println(params[0]);
}
moreover,why it doesn't treat the array as a single parameter (line 1)
Output from running the above is:
1
[I#3e25a5
In java every function with (X... ) signature takes an array of X as parameter.
In your first example you get warning that you're passing the array of Integers as vararg Object without a cast. Java is clever enough to thing that you probably wanted to pass it as Object[] instead of a single Object. If you add a cast to Object[] the warning disappears.
In the second example the array is pàssed as only THE FIRST vararg, as every array is an object. It can't be passed as an array of object, because it's an array of primitives.
Arrays of any type are objects as you can verify running this snippet of code
public class Test{
public static void test(Object a) {
System.out.println("ok");
}
public static void main(String args[]){
int[] i = {1,2,3,4};
test(i);
}
}
It prints "ok", which means that int[] is an Object.
~
I just tried your code, and I get:
1
[I#71f6f0bf
The thing is, your method takes an array of Object by varargs. So, for the first call, params is an array of 3 elements containing each individual Integer. However, ints are not Objects (int's Wrapper class, Integer, is, but int isn't), so for the second call, params is an array of a single element containing the actual array object. That gibberish above is the output of an array's toString() method.
If you would have replace the varargs call with a Object[], the second call would not have compiled, because an int[] is not a Object[].
Object... interprets an array as a list of arguments, not as a single object.
Why not use a Set as a container instead?

Categories

Resources