2012-02-28 14 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; 
    } 
}