java传值和通过引用传递
生活随笔
收集整理的這篇文章主要介紹了
java传值和通过引用传递
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
第一次使用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)置基本類型和對象是通過轉(zhuǎn)移。
版權(quán)聲明:本文博客原創(chuàng)文章,博客,未經(jīng)同意,不得轉(zhuǎn)載。
總結(jié)
以上是生活随笔為你收集整理的java传值和通过引用传递的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Entity Framework中使用I
- 下一篇: Java中间件:淘宝网系统高性能利器