`
Jawfneo
  • 浏览: 860 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Pay Attention to the Reference of Java

阅读更多

   
     今天调试了个这样的一个问题,在Java中很容易就会忽略了引用的问题,一不小心就被会这实质为指针的引用给隐藏了臭虫,若没调试我就中了这招。

我用以下的例子来展现这样的问题:
我们定义两个类:Drawer和Apple
/**
 * Object Apple
 */
public class Apple {
	private String color;

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
}
 
/**
 * Object Drawer that is used to put apples.
 * Actually, it is used to put appleBox which is used to put apples.
 */
public class Drawer {
	private List<Apple> appleBox;

	public Drawer() {
		appleBox=new ArrayList<Apple>();
	}

	public Drawer(List<Apple> appleBox) {
		this.appleBox = appleBox;
	}
	
	public void putAppleToBox(Apple apple){
		this.appleBox.add(apple);
	}
	
	public void setAppleBox(List<Apple> appleBox) {
		this.appleBox = appleBox;
	}

	public List<Apple> getAppleBox(){
		return appleBox;
	}
}
      Our test case is :
    public void testDrawer(){		
		Drawer drawer=new Drawer();
		Apple apple=new Apple();
		apple.setColor("Red");
		drawer.putAppleToBox(apple);
		System.out.println(drawer.getAppleBox().get(0).getColor());
		System.out.println("---------");
		
		Drawer drawer2=new Drawer();
		drawer2.setAppleBox(drawer.getAppleBox());//关键所在	
		Apple apple2=new Apple();
		apple2.setColor("Yellow");
		drawer2.putAppleToBox(apple2);
		System.out.println(drawer.getAppleBox().size());
		System.out.println(drawer2.getAppleBox().size());
		System.out.println("---------");
		drawer2.getAppleBox().get(0).setColor("Green");
		System.out.println(drawer.getAppleBox().get(0).getColor());
		System.out.println(drawer.getAppleBox().get(1).getColor());
		System.out.println(drawer2.getAppleBox().get(0).getColor());
		System.out.println(drawer2.getAppleBox().get(1).getColor());		
	}
 The test result will be:
Red
---------
2
2
---------
Green
Yellow
Green
Yellow
 经验丰富的程序员可能一眼就看出来这样一个实质问题:这里的AppleBox的ArrayList实例只有一个。两个抽屉里面的appleBox引用指向的是同一个ArrayList实例。
这里有个误区,就是以为new了两个抽屉的实例就以为万事大吉了。
当使用drawer2.setAppleBox(drawer.getAppleBox());时,只是将drawer2的appleBox引用指向drawer的appleBox指向的实例。

我们再简化上面的程序:
Apple不变,讲抽屉简化只能放一个苹果,去掉AppleBox这个类:
/**
 * Object Drawer that is used to put one apple.
 */
public class Drawer {
	private Apple apple;

	public Drawer() {		
	}

	public void putApple(Apple apple){
		this.apple=apple;
	}
	
	public Apple getApple(){
		return apple;
	}
}
   Our Test case :
    public void testDrawer(){
		Drawer drawer=new Drawer();
		Apple apple=new Apple();
		apple.setColor("Red");
		drawer.putApple(apple);
		System.out.println(drawer.getApple().getColor());
		
		Drawer drawer2=new Drawer();
		drawer2.putApple(drawer.getApple());
		drawer2.getApple().setColor("Green");
		System.out.println(drawer.getApple().getColor());
		System.out.println(drawer2.getApple().getColor());			
    }
 The test result will be:
Red
Green
Green
其实实质是一样的,这里的Apple实例只有一个,两个抽屉的apple引用指向同一个Apple实例。

总结:
1. Java中的Reference实质就是指针;
2. 使用他,你得特别地注意了。

分享到:
评论

相关推荐

    The application of Factor Analysis in Chinese Stock Market

    The application of Factor Analysis in Chinese Stock Market,孙鑫,,In this article, we pay attention to the fundamental of the listed companies. We acquire the 2008 medium-term financial targets of ...

    Optimizing Java_Practical Techniques for Improving JVM Application Performance

    You might pay more attention to the performance of connections between services than of the services themselves. If you make business decisions for your company, application performance will probably...

    JavaApplication3.rar_The First

    It was to fix different types of methods and their applications. First of all, should pay attention to the return type of the method, and the type of arguments and operations on them.

    weixin-java-pay-2.8.0-API文档-中文版.zip

    赠送jar包:weixin-java-pay-2.8.0.jar; 赠送原API文档:weixin-java-pay-2.8.0-javadoc.jar; 赠送源代码:weixin-java-pay-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-pay-2.8.0.pom; 包含翻译后...

    weixin-java-pay-3.5.0-API文档-中文版.zip

    赠送jar包:weixin-java-pay-3.5.0.jar; 赠送原API文档:weixin-java-pay-3.5.0-javadoc.jar; 赠送源代码:weixin-java-pay-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-pay-3.5.0.pom; 包含翻译后...

    The Art of Unix Programming

    So we will pay more attention to non-Unix environments (especially Microsoft operating systems) than is usual in a Unix book; and when tools and case studies are portable, we'll say so. You should ...

    java第二次试验

    The description "java 第二次试验,云大java试验,第二次java实验" provides a brief overview of the report, stating that this is a Java experiment report, specifically the second one, conducted at Yunnan...

    LTE The UMTS Long Term Evolution

    The authors not only pay special attention to the physical layer, giving insight into the fundamental concepts of OFDMA, SC-FDMA and MIMO, but also cover the higher protocol layers and system ...

    citywar_wave7t5_citywar_AllOut_YouWillPay_

    On the other hand if losing a city will cost us too much to rebuild the connection we must pay more attention to that city.Given the map of cities which have all the destroyed and remaining highways ...

    C Programming - Just the FAQS

    attention to the questions regarding the switch statement and operator precedence, because these elements of the C language sometimes can be confusing for the beginning C programmer.

    Support Vector Machines

    This note is about the Support Vector Machines (SVM), a method that has exhibited excellent accuracy in classication...domains, and we encourage the readers to also pay attention to these aspects of SVM.

    bec官方考试报告解析

    1.pay attention to the complete meaning of the sentences in Part1 要注意理解阅读第一部分给出的所有句子,每句句子的意思都要做到完全理解。 2.read the whole text in Part2 and try to predict what kind ...

    支付宝源码工程

    【旧版本】 下载之后解压有【MD5签名版本和RSA签名版本】文件 MD5签名版本 |————create_direct_pay_by_user-CSHARP-GBK |————create_direct_...支付宝官方例子工程源码---alipay.trade.page.pay-JAVA-UTF-8

    Solaris.10-The.Complete.Reference

    This book is intended as an easy-to-access reference point for Solaris 10, the latest version of the enterprise network operating system developed by Sun Microsystems. Solaris 10 is now free for all ...

    weixin-java-pay-3.5.0-API文档-中英对照版.zip

    赠送jar包:weixin-java-pay-3.5.0.jar; 赠送原API文档:weixin-java-pay-3.5.0-javadoc.jar; 赠送源代码:weixin-java-pay-3.5.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-pay-3.5.0.pom; 包含翻译后...

    腾达Tenda w311r H1-3.3.6d最新固件

    please pay attention to the firmware version before upgrade the firmware version begin with H1 can't upgrade to the firmware verson begin with H3 or V3.2.4.02 the firmware version begin with H3 can'...

    Write Java program called AverageNumbers

    在这个Java编程实验中,我们主要关注了三个不同的程序:AverageNumbers、FarheheitToCentigrade和Payroll。这些程序分别涉及数值计算、温度转换和薪资计算,它们都是基于Java语言的基本语法和数学运算。 首先,`...

    ods-java-data-struction.pdf

    The goal of this project is to free undergraduate computer science stu- dents from having to pay for an introductory data structures book. I have decided to implement this goal by treating this book ...

Global site tag (gtag.js) - Google Analytics