开发者

Is it safe to re-use variables inside a method?

开发者 https://www.devze.com 2023-02-11 07:59 出处:网络
I have an array of type string which I want to re-use inside a method. I need to pass it to a function which returns a subset of the elements of array passed. To capture the returned array from funct

I have an array of type string which I want to re-use inside a method.

I need to pass it to a function which returns a subset of the elements of array passed. To capture the returned array from function, should I declare a new string array or can I safely re-use same array that was holding the unfiltered array to hold filtered array ??

Also clarify that, when I pass a variable like arr开发者_Python百科ay to a function does it creates a new space for the array in the heap each time I pass it as parameter to further functions or just it uses the same space in the heap & just passes the reference? I guess in case of array it passes just the reference but in case of simple variables it allocates new space on stack, right?

EDIT: Thanks you all for the great answers and explanations!!

Please also clarify whether that if I am reusing the array, would I be required to set the null at the position when I end the subset of array ? (Actually the subset of my array is not directly calculated from the array but some other calulations, so I would be required to manually set the null otherwise the older elements of the list would be visible, right??)


when I pass a variable like array to a function does it creates a new space for the array in the heap each time I pass it as parameter to further functions or just it uses the same space in the heap & just passes the reference

Java is entirely pass by value, but with arrays and object types, the value being passed is a reference (pointer) to the actual object, which is not duplicated. So when you pass an array into a function, only the reference to the array is copied; the array itself isn't. That's why if a function modifies the contents of an array, the code calling the function sees the modifications.

Example:

// A method that changes the first entry in an array
void changeArray(String[] theArray) {
    theArray[0] = "Updated";
}

// A method that uses the above
void someMethod() {
    String[] foo = new String[3];
    foo[0] = "Original 0";
    foo[1] = "Original 1";
    foo[2] = "Original 2";

    this.changeArray(foo); // `changeArray` receives a *copy* of the reference
                           // held in `foo`; both references point to the same
                           // array

    System.out.println(foo[0]); // Prints "Updated"
}

Passing a reference into a method is exactly like assigning it to another reference variable:

String[] foo = new String[3]; // Create a new aaray, assign reference to `foo` variable
String[] bar = foo;           // Copy the reference into `bar` as well
foo[0] = "Hi there";          // Use the reference in `foo` to assign to the first element
System.out.println(bar[0]);   // Use the reference in `bar`, prints "Hi there"

Essentially, references are values (numbers) that tell the JVM where the data for an object is. So even when we copy a reference (because Java is entirely pass-by-value, the value of the reference is passed to the function), it still points to the same memory as the original.

Since the reference is passed into the function by value, the function can't change the calling code's reference:

// A method that assigns a new reference; the calling code sees no change
void changeReference(String[] theArray) {
    theArray = new String[1];        // Now we're not using the caller's object anymore
    theArray[0] = "I was changed";
}

// A method that uses the above
void someMethod() {
    String[] foo = new String[3];
    foo[0] = "Original 0";
    foo[1] = "Original 1";
    foo[2] = "Original 2";

    this.changeReference(foo);
    System.out.println(foo[0]); // Prints "Original 0", our reference wasn't changed
}

You'll note that this is exactly how primitives are treated:

void whatever(int a) {
    a = 5;
}
void someMethod() {
    int foo;

    foo = 3;
    whatever(foo);
    System.out.println(foo); // Prints 3, of course, not 5
}

...and in fact, object references (as opposed to objects) are primitives.

...should I declare a new string array or can I safely re-use same array that was holding the unfiltered array to hold filtered array

You can safely re-use it if that's appropriate within the scope of your function. It may be more appropriate to declare a new variable (e.g., filteredThingy), but that's a matter of style and will depend on the situation.


You probably can by it is very bad style and is very error prone and is very unsafe for future modifications.

Here is the example.

public void foo(String[] args) {
    // do something with array.

    args = new String[] {"a", "b"};  // reuse of the array.

    // more code.

    for (Sring s : args) {
        // what will this loop get"? 
        // The answer is: a, b
        // but will you remember this fact in a month if "more code" above is 50 lines long?
    }

}


Passing objects is essentially passing references. E.g., your array will only exist in one place in memory when passing it between functions. Here's a runnable example illustrating that.

If you like you can reuse the same array in your routine. Note that changes made to that array will be visible to all objects sharing the same reference to that array. If that's not desirable then you must declare a new array.


String parentArray = {"S","B","R"};


// no need to use new operator to hold subSetArray.
String subSetArray = returnSubSet(parent);

public String[] returnSubSet(String[] _parent)
{
    return Arrays.copyOfRange(_parent,1,2);
}

, when I pass a variable like array to a function does it creates a new space for the array in the heap each time I pass it as parameter to further functions or just it uses the same space in the heap & just passes the reference?

Answer      
 1. Object in Java are  Pass by reference by value
 2. when you pass an array to a function , a _parent variable will be created in stack and it points to the same Array Object in heap.

UPDATES: Primitive example

int global_scope_variable=10;

setValue(global_scope_variable);

public void setValue(int val)
{
    // val is visible only within this method.

    System.out.println(val);    // output is 10
    val=20;
    System.out.println(val);    // output is 20
    System.out.println(global_scope_variable);  // output is 10   
}
0

精彩评论

暂无评论...
验证码 换一张
取 消