java - 關于引用對象的問題
問題描述
能不能詳細解釋下為什么最后y會隨著x的變化而變化
Point x = new Point(0,0);Point y = new Point(1,1);x = y;x.setLocation(5,5);System.out.println('x is :'+x);System.out.println('y is :'+y);
程序運行結果:
x is java.awt.Point[x=5, y=5]y is java.awt.Point[x=5, y=5]
問題解答
回答1:x和y變量存在棧中,分別指向new Point(0,0)和new Point(1,1)這兩個堆中的對象,執(zhí)行x = y,x把引用指向y內(nèi)存中的地址,x.setLocation(5,5),直接對y進行了修改,最后x和y都指向堆中的y,所以打印的都是x修改的內(nèi)容x=5, y=5
回答2:google 值傳遞和引用傳遞思考問題:最后輸出結果是什么?public class User { private String name; public User(String name) {this.name = name; }public String getName() {return name; } public void setName(String name) {this.name = name; }}
public class Test { public static void main(String[] args) {User u = new User('張三');changeUser(u);System.out.println(u.getName()); } public static void changeUser(User user){user.setName('李四');user = new User('王五');user.setName('趙六'); }}回答3:
那是,你引用的全是y的空間地址
相關文章:
1. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””2. docker-compose中volumes的問題3. boot2docker無法啟動4. nignx - docker內(nèi)nginx 80端口被占用5. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.6. docker容器呢SSH為什么連不通呢?7. node.js - antdesign怎么集合react-redux對input控件進行初始化賦值8. dockerfile - 為什么docker容器啟動不了?9. java - SSH框架中寫分頁時service層中不能注入分頁類10. 關于docker下的nginx壓力測試

網(wǎng)公網(wǎng)安備