Java中的按值傳遞和按引用傳遞的代碼詳解
先使用int實驗:
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; } }
輸出:a = 0
這說明對于int值是按值傳遞。其他幾個基本類型也是如此。
再使用自己定義的類UserEntity來實驗:
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("猿猴"); changeName(userEntity); System.out.println("name = "+userEntity.getName()); } public static void changeName(UserEntity userEntity){ userEntity.setName("忽必烈"); } }
輸出:name = 忽必烈
我們再來使用一個linkedList<Object>來實驗:
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("石頭"); addUser(userEntity); System.out.println("name = "+userEntity.getName()); } public static void addUser(UserEntity userEntity){ mList.add(userEntity); mList.get(0).setName("猿猴"); } }
輸出:name= 猿猴
這說明在使用我們自己定義的類時,是按引用傳遞的。
接著,再來使用String實驗:
public class TTEST { public static void main(String[] args) { String str= "開始的"; changeStr(str); System.out.println("str = "+str); } public static void changeStr(String str){ str = "改變的"; } }
輸出:str = 開始的
用Integer做實驗也會發(fā)現(xiàn)沒有改變。
說明我們按照java內(nèi)置的對象也是值傳遞。因此我們可以做如下總結(jié):
只要我們自己定義的類創(chuàng)建的對象,都是引用傳遞,系統(tǒng)內(nèi)置的基本類型和對象都是指傳遞。
總結(jié)
以上所述是小編給大家介紹的Java中的按值傳遞和按引用傳遞,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Java?多線程并發(fā)編程提高數(shù)據(jù)處理效率的詳細過程
這篇文章主要介紹了Java?多線程并發(fā)編程提高數(shù)據(jù)處理效率,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04詳解@ConfigurationProperties實現(xiàn)原理與實戰(zhàn)
這篇文章主要介紹了詳解@ConfigurationProperties實現(xiàn)原理與實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10新版本IntelliJ IDEA 構(gòu)建maven,并用Maven創(chuàng)建一個web項目(圖文教程)
這篇文章主要介紹了新版本IntelliJ IDEA 構(gòu)建maven,并用Maven創(chuàng)建一個web項目的圖文教程,需要的朋友可以參考下2018-01-01在eclipse導(dǎo)入Java的jar包的方法JDBC(圖文說明)
這篇文章主要介紹了在eclipse導(dǎo)入Java 的jar包的方法 JDBC 圖文說明 ,需要的朋友可以參考下2015-09-09