First use int experiment:
public class TTEST { private static List<UserEntity> mList = new LinkedList<UserEntity>(); public static void main(String[] args) { int a = 0; changeA(a); System.out.println("a = "+a); } public static void changeA(int a){ a = 1; } }Output: a = 0
This means that for int values is passed by value. The same is true for several other basic types.
Then use the UserEntity class you defined to experiment:
public class UserEntity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class TTEST { public static void main(String[] args) { UserEntity userEntity = new UserEntity(); userEntity.setName("Ape"); changeName(userEntity); System.out.println("name = "+userEntity.getName()); } public static void changeName(UserEntity userEntity){ userEntity.setName("Kublai"); } }Output: name = Kublai Khan
Let's use a linkedList<Object> to experiment:
import java.util.LinkedList; import java.util.List; public class TTEST { private static List<UserEntity> mList = new LinkedList<UserEntity>(); public static void main(String[] args) { UserEntity userEntity = new UserEntity(); userEntity.setName("Stone"); addUser(userEntity); System.out.println("name = "+userEntity.getName()); } public static void addUser(UserEntity userEntity){ mList.add(userEntity); mList.get(0).setName("Ape"); } }Output: name= Ape
This shows that when using classes we define ourselves, they are passed by reference.
Next, let’s use String experiment:
public class TTEST { public static void main(String[] args) { String str= "start"; changeStr(str); System.out.println("str = "+str); } public static void changeStr(String str){ str = "changed"; } }Output: str = start
Using Integer to do experiments will also find that there is no change.
This shows that we pass the built-in objects in Java as well. Therefore, we can make the following summary:
As long as the objects created by the class we define ourselves are reference passes, the basic types and objects built into the system refer to passes.
Summarize
The above is the value-based and reference-based delivery in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!