[Java] function parameter passing analysis

First, let me Conclusion: Java parameter passing, you can not modify data point, the data can only be modified property

Java function parameter passing, for the non-reference type (basic data types, such as int, float, etc.), the reference transfer function is no effect of the modifications

For reference data types, classes (interfaces), arrays, enumerations, modified, only modify the properties of the data, but can not modify "the data itself points"

This is beginning to sound very abstract, but Java is so unlike C and C ++ have two hands, you can modify the data point to a function in python reference to the type of treatment a bit like, Java can not modify the data point

Compare:

Java: For an array of classic mass participation, java String in itself is immutable

str = "hello" invalid modify itself, and c = new char [] { '0', '0', '0', '0'} is attempting to modify itself, which is ineffective in Java

public class T2 {
	public static void change (String str, char c[]) {
		str = "Hello";
		c = new char[] {'0','0','0', '0'};
		c[0] = 'M';
	}
	public final static void main(String[] args) {
		String str = new String("Hello world");
		char cString [] = new char[] {'h', 'e', 'l', 'l', 'o'};
		change(str, cString);
		System.out.println("str = "+str);
		for(char c : cString) {
			System.out.print(c);
		}
		System.out.println();
	}
}

operation result:

The results showed that: a modified two results that are not

But we can modify the properties of the data in Java:


public class T2 {
	public static void change (String str, char c[]) {
		str = "Hello";
//		c = new char[] {'0','0','0', '0'};
		c[0] = 'M';
	}
	public final static void main(String[] args) {
		String str = new String("Hello world");
		char cString [] = new char[] {'h', 'e', 'l', 'l', 'o'};
		change(str, cString);
		System.out.println("str = "+str);
		for(char c : cString) {
			System.out.print(c);
		}
		System.out.println();
	}
}

After trying to change the code point commented above, this case is not a temporary modification in the stack apart from this memory (new char [] { '0', '0', '0', '0'}), but modified incoming reference attribute type itself, so effective

Output:

Compare python:

python does not support function to modify points

class Stu:
    def __init__(self, name):
        self.name = name

    def say(self):
        print(self.name, "is saying")


def change_dir(person):
    person = Stu("xiaohong")
    person.say()

def main():
    xiaoming = Stu("xiaoming")
    xiaoming.say()
    change_dir(xiaoming)
    xiaoming.say()

if __name__ == "__main__":
    main()

operation result:

C and C ++ is not a way of example, a pointer to the content, and the Java, Python same effect

Two pointers point to modify, in operation no such Java, Python, of course, not

Guess you like

Origin blog.csdn.net/chenhanxuan1999/article/details/91488384