2012-02-28 86 views
8

我很惊讶地看到,heightwidth成员的获得者有return类型double,尽管它们是int。此外,setSize方法双参数的定义如下:java.awt的Dimension类中的方法返回类型

/** 
* Sets the size of this <code>Dimension</code> object to 
* the specified width and height in double precision. 
* Note that if <code>width</code> or <code>height</code> 
* are larger than <code>Integer.MAX_VALUE</code>, they will 
* be reset to <code>Integer.MAX_VALUE</code>. 
* 
* @param width the new width for the <code>Dimension</code> object 
* @param height the new height for the <code>Dimension</code> object 
*/ 
public void setSize(double width, double height) { 
    this.width = (int) Math.ceil(width); 
    this.height = (int) Math.ceil(height); 
} 

请看看Dimension类。以上评论说,值不能超出Integer.MAX_VALUE。为什么? 为什么我们有double?有没有什么微妙的原因?任何人都可以向我解释这个吗?对我的坚持抱歉!

回答

3

java.awt.Dimension被改型以装配到java.awt.geom包,以便它可以任何需要Dimension2D使用。后面的接口处理浮点,所以Dimension也必须。限于int字段,只能表示double的一个子集。 Dimension2D.Float也同样受到限制。

3

该类存储heightwidthint,它只是提供了双接受过这样你就可以用双值调用它(但他们会立即强制转换为int)的方法。在这个文件中还有其他setSize()方法接受int值或者甚至是一个Dimension对象。

并且由于这些值存储为int,当然它们的最大值是Integer.MAX_VALUE

+1

那就是它?为什么我们有'double'作为'return'类型的getter?有用吗? – Ahamed 2012-02-28 18:38:39

+0

我不知道他们为什么返回为double的确切原因(可能是因为当谈论维度时,你谈论的是精度,而double更多地用于这些情况),但对于setters来说,它只是一些方法重载帮助用户。 – talnicolas 2012-02-28 18:41:30

+0

感谢您的回复,我不认为具有int值的double将有助于提高精度。我的意思是双1517.00等于1517,所以肯定有一些原因? – Ahamed 2012-02-28 18:44:54

0

您可以使用带有ints的java Dimension类。如果您需要双倍宽度和高度的Dimension类,您可以使用以下内容:

public class DoubleDimension { 
    double width, height; 

    public DoubleDimension(double width, double height) { 
     super(); 
     this.width = width; 
     this.height = height; 
    } 

    public double getWidth() { 
     return width; 
    } 

    public void setWidth(double width) { 
     this.width = width; 
    } 

    public double getHeight() { 
     return height; 
    } 

    public void setHeight(double height) { 
     this.height = height; 
    } 

    @Override 
    public String toString() { 
     return "DoubleDimension [width=" + width + ", height=" + height + "]"; 
    } 

    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     long temp; 
     temp = Double.doubleToLongBits(height); 
     result = prime * result + (int) (temp^(temp >>> 32)); 
     temp = Double.doubleToLongBits(width); 
     result = prime * result + (int) (temp^(temp >>> 32)); 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) 
      return true; 
     if (obj == null) 
      return false; 
     if (getClass() != obj.getClass()) 
      return false; 
     DoubleDimension other = (DoubleDimension) obj; 
     if (Double.doubleToLongBits(height) != Double.doubleToLongBits(other.height)) 
      return false; 
     if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width)) 
      return false; 
     return true; 
    } 
}