我的代码在使用ArrayList
包含对象的测试时有效,但在arrayList
为空时会出现以下错误:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
我怎么了?
获取Rectangle
面积最小的返回面积最小的矩形,或者null
如果没有矩形。
import java.util.ArrayList;
public class RectangleList
{
ArrayList<Rectangle> list = new ArrayList<Rectangle>();
public RectangleList(ArrayList<Rectangle> theList)
{
list = theList;
}
/**
* Gets the Rectangle with the smallest area
*
* @return the rectangle with the smallest area or null if there are no
* rectangles
*
*/
public Rectangle smallestArea()
{
Rectangle currentsmallestRectangle = list.get(0);
for (int i = 0; i < list.size(); i++) {
Rectangle nextRectangle = list.get(i);
if (list.isEmpty()) {
return null;
} else if ((nextRectangle.getWidth() * nextRectangle.getHeight()) < (currentsmallestRectangle
.getWidth() * currentsmallestRectangle.getHeight())) {
currentsmallestRectangle = nextRectangle;
}
return currentsmallestRectangle;
}
}
}