do you mean like this?
int[] dim1 = myObject.getCoord();
public int[] getCoord() {
return new int[] {y1, x1} ;
}
only one array is ever created, by the method call, and only has one reference, dim1.
but ideally you probably don't want a "get" method to be creating new things, as just by looking at the declaration you might not expect that. personally, i'd prefer
int[] dim1 = myObject.createCoord();
public int[] createCoord() {
return new int[] {y1, x1} ;
}
which makes it explicit that the method is "creating" a thing.
Answer from John Gardner on Stack Overflowdo you mean like this?
int[] dim1 = myObject.getCoord();
public int[] getCoord() {
return new int[] {y1, x1} ;
}
only one array is ever created, by the method call, and only has one reference, dim1.
but ideally you probably don't want a "get" method to be creating new things, as just by looking at the declaration you might not expect that. personally, i'd prefer
int[] dim1 = myObject.createCoord();
public int[] createCoord() {
return new int[] {y1, x1} ;
}
which makes it explicit that the method is "creating" a thing.
No matter how you try to shorten your code, it doesn't change the fact that when the call to getCoord() returns, it simply returns a reference to the array, not a copy of the contents of the array.
Trying to make the code more succinct won't help you with your performance problem.
Just don't initialize dim1 to new int[2]; at the beginning if you want, because it gets replaced right after anyways. But that's small potatoes.
How do you return an array in a method?
Returning Arrays in Java - Stack Overflow
java - Return array of multiple different objects? - Software Engineering Stack Exchange
java - Return array pointers vs. populating an array inserted as a parameter? - Software Engineering Stack Exchange
Videos
Today, I had a interview but I failed miserably in the first coding test. And before I can finish it, the interviewer just hung up the phone....sob sob
I am completely stumped how to do this question and have spent the last 2 hours figuring out to no avail and I hope to be able to get some helps here.
So, you are given an array = {1,2,6,4,5}
And a target no say 10.
The method must return the answer in {6,4}.
How can I achieve it ?
Here's my lame attempt:
public static int[][]ab(int[]arr, int target){
target = 10;
int[][]temp = null;
int a = 0; int b = 0;
int sum = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = i; j < arr.length; j++) {
a = arr[i];
b = arr[j];
if ( a + b == 10) {
System.out.printf("Pair : " + arr[i], arr[j] );
}
}
}
return temp;// i do not know how to put arr[i] and arr[j] and store it in a array
}Tks.
It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.
When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:
public static void main(String[] args) {
{1,2,3};
}
Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:
public static void main(String[] args){
int[] result = numbers();
for (int i=0; i<result.length; i++) {
System.out.print(result[i]+" ");
}
}
Of course the method numbers() returns an array, it's just that you're doing nothing with it. Try this in main():
int[] array = numbers(); // obtain the array
System.out.println(Arrays.toString(array)); // now print it
That will show the array in the console.
Is this considered good practice in terms of writing clean code?
Hell, no! It's horrible.
What would be the alternatives?
Create a class which has those things as fields and return an instance of that class. Furthermore, that class can have methods which use the data to do useful things. That's what OOP means: put the logic where the data is instead of ferrying around the data between procedures.
No, this is bad practice. The proper solution is to create a class of your own with members of the appropriate types.
There are many reasons why this is better:
There is no possibility of forgotten, wrong or subtly wrong typecasts. Instead of slow, risky manual casts you get automatic, efficient storage verified by the compiler.
The members can have descriptive names instead of hard-to-remember positions in the nondescript Arrays.
You can pass around multiple values in one object if you ever need them together in another place of your program (and experience teaches that you often will).
In classical C, returning an array from a function isn't as easy as in Java. That's why C functions often choose to populate an array passed in from the caller, whereas Java methods typically follow the natural data flow, i.e. returning the results as array.
So in Java you can (and should) follow the natural data flow, i.e. returning a fresh array from the method. In C, although it's counter-intuitive, it's often better to have the caller provide the array - C programmers are used to that style.
Let me explain my reasoning:
C style
If you want to return an array from a function, you have to allocate it dynamically (it can't be on the stack as that wouldn't survive leaving the function, and it can't be static, because then multiple function calls would get mixed up). To the caller, that means that he gets responsible for eventually freeing the array.
The caller needs to know how long the array is, so he doesn't access invalid elements. As an array result (e.g. int[]) is in fact just a pointer to its element type (int *), there's no place to communicate the length.
So in C, there's no easy and natural way to return an array from a function.
(Of course, that's only classical C, and later versions added much of the features that classical C lacked, but many library functions were already defined early...).
Java style
Arrays are always created in dynamic memory (on the heap), but that's managed by the JVM. So the caller has no duty of freeing any memory, because that's done by the garbage collector.
Also there's no problem with the array length as Java arrays know their length.
From a semantic perspective, returning an array from the method suggests that it's a different array than the one you passed in. That's why the accepted C style, when modifying an array in place, is to modify the array that is passed in, in place. Returning a new collection is more common in Java than it is in C, which is why you see it being passed out of the function as a return value.
An array in C is really just a pointer to a typed value; C doesn't even know how long an array is if you allocated it dynamically, making it difficult for a caller to handle a returned array. Arrays in Java contain metadata, such as the length of the array and the type of its members, making it easier for methods to return new arrays and for callers to consume them.
Note that you can still modify an existing array in-place in Java if you wish, in which case you would do the same thing in Java that you would in C: modify the passed-in array parameter in-place.
C pointers and Java references are not the same thing, even though they are used to accomplish similar objectives. In C, a pointer is an actual memory address. Pointer arithmetic is possible in C, where it is actually used to allocate memory and dereference array members and struct members.
In Java, references are an implementation detail, not a memory address. You cannot perform pointer arithmetic on them, nor can you make any assumptions at all about how they work under the hood from a memory perspective, because the Java language specification does not stipulate how they are to be implemented.
This difference is further highlighted in the treatment of zero-length arrays: they don't exist in C, except as the last member of a struct.