java.awt的Dimension类中的方法返回类型



我很惊讶地发现heightwidth成员的getter具有return类型double,尽管它们是int。此外,具有双参数的setSize方法具有以下定义:

/**
 * 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介于两者之间?有什么微妙的原因吗?有人能向我解释一下吗?对不起我的坚持!

java.awt.Dimension经过改装以适应java.awt.geom包,因此可以在需要Dimension2D的任何地方使用。后面的接口处理浮点,所以Dimension也必须处理。由于限于int字段,因此只能表示double的子集。CCD_ 14也受到类似的限制。

该类将heightwidth存储为int,它只是提供了一个也接受double的方法,因此您可以用double值调用它(但它们会立即转换为int)。该文件中还有其他接受int值甚至Dimension对象的setSize()方法。

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

您可以将java Dimension类与int一起使用。如果你需要一个宽度和高度加倍的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;
    }
}

最新更新