Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Single Element Array Inline

Tags:

java

arrays

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]);
like image 955
Dzhuneyt Avatar asked Nov 09 '12 11:11

Dzhuneyt


3 Answers

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>};
like image 188
Sumit Singh Avatar answered Oct 26 '22 15:10

Sumit Singh


try

int[] pidArray = new int[]{ mySinglePID };
am.getProcessMemoryInfo(pidArray);

oneliner would be

am.getProcessMemoryInfo(new int[]{mySinglePID });
like image 40
PermGenError Avatar answered Oct 26 '22 14:10

PermGenError


You can do it like this: -

am.getProcessMemoryInfo(new int[]{ mySinglePID });

So, you don't need to declare your array variable here. Just pass an unnamed array object.

like image 37
Rohit Jain Avatar answered Oct 26 '22 15:10

Rohit Jain