解析Java代码经常出现的错误(2)

来源:IT的点点滴滴 责任编辑:栏目编辑 发表时间:2013-07-01 12:29 点击:

五、常见错误5#:拷贝错误的数据

有时候程序员知道必须返回一个拷贝,但是却不小心拷贝了错误的数据。由于仅仅做了部分的数据拷贝工作,下面的代码与程序员的意图有偏差:

 

  1. import java.awt.Dimension;
  2. /*** Example class. The height and width values should never * be
  3. negative. */
  4. public class Example{
  5. static final public int TOTAL_VALUES = 10;
  6. private Dimension[] d = new Dimension[TOTAL_VALUES];
  7. public Example (){ }
  8. /*** Set height and width. Both height and width must be nonnegative * or
  9. an exception will be thrown. */
  10. public synchronized void setValues (int index, int height, int width)
  11. throws IllegalArgumentException{
  12. if (height < 0 || width < 0)
  13. throw new IllegalArgumentException();
  14. if (d[index] == null)
  15. d[index] = new Dimension();
  16. d[index].height = height;
  17. d[index].width = width;
  18. }
  19. public synchronized Dimension[] getValues()
  20. throws CloneNotSupportedException{
  21. return (Dimension[])d.clone();
  22. }
  23. }

 

这儿的问题在于getValues()方法仅仅克隆了数组,而没有克隆数组中包含的Dimension对象,因此,虽然调用者无法改变内部的数组使其元素指向不同的Dimension对象,但是调用者却可以改变内部的数组元素(也就是Dimension对象)的内容。方法getValues()的更好版本为:

 

  1. public synchronized Dimension[] getValues() throws CloneNotSupportedException{
  2. Dimension[] copy = (Dimension[])d.clone();
  3. for (int i = 0; i < copy.length; ++i){
  4. // NOTE: Dimension isn’t cloneable.
  5. if (d != null)
  6. copy[i] = new Dimension (d[i].height, d[i].width);
  7. }
  8. return copy; <

    相关新闻>>

      发表评论
      请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
      用户名: 验证码:点击我更换图片
      最新评论 更多>>

      推荐热点

      • Java编程语言的八大优点
      • JVM对象生命周期详细介绍
      • Java平台上的CRM系统
      • Java 算数测试小程序
      • Command(命令模式)
      • Java 一个简单的画图程序
      • Java环境 使用Resin在NT环境下配置JSP环境
      • Java 日历的小程序
      • Java 统计代码的小工具
      网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
      Copyright © 2008-2015 计算机技术学习交流网. 版权所有

      豫ICP备11007008号-1