Java – Passing Single Element Array Inline

arraysjava

I am new to Java and this I have encountered several functions that accept an array of given elements (e.g. int[]). However, there are cases where I just have one int to pass and I was wondering how to do this inline (e.g. without defining an array variable first).

For example, how to simplify this:

int[] pidArray = { mySinglePID };
am.getProcessMemoryInfo(pidArray); // This one accepts arrays only

To something like (made up, doesn't work this way):

am.getProcessMemoryInfo([mySinglePID]);

Best Answer

Just use Anonymous Array for your code:

am.getProcessMemoryInfo(new int[]{mySinglePID }); // This one accepts arrays only

Anonymous Array: In java it is perfectly legal to create an anonymous array using the following syntax.

new <type>[] { <list of values>};