My code works when tested with an ArrayList
that contain objects but puts out the following error when the arrayList
is empty:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
What am I getting wrong?
Gets the Rectangle
with the smallest area
return the rectangle with the smallest area or null
if
there are no rectangles.
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;
}
}
}
Hi my code works when tested with ArrayLists that contain objects but puts out the error java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 when the arrayList is empty. What am I getting wrong.
ArrayList.get()
is behaving exactly as documented.
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size()
)
There are no entries, so index 0 is out of bounds. If you want to return null
if there are no rectangles, you should do that explicitly:
// Alternatively, if list.size() == 0
if (list.isEmpty()) {
return null;
}
Note that a reference to an empty list is very different from a null reference, by the way. (Your title refers to a "null arrayList" - there's no such thing as a null object, but there can be a null reference... except there isn't in your case.)
This needs to be done before you otherwise call list.get(0)
- and only once. (What's the point of calling it in the loop?) For example:
public Rectangle smallestArea() {
if (list.isEmpty()) {
return null;
}
Rectangle currentsmallestRectangle = list.get(0);
// Note that you can go from 1, not 0...
for (int i = 1; i < list.size(); i++) {
Rectangle nextRectangle = list.get(i);
if ((nextRectangle.getWidth() * nextRectangle.getHeight()) <
(currentsmallestRectangle.getWidth() *
currentsmallestRectangle.getHeight())) {
currentsmallestRectangle = nextRectangle;
}
}
return currentSmallestRectangle;
}
Ideally, add an area()
method to your Rectangle
class, to make the loop simpler:
for (int i = 1; i < list.size(); i++) {
Rectangle nextRectangle = list.get(i);
if (nextRectangle.area() < currentSmallestRectangle.area()) {
currentsmallestRectangle = nextRectangle;
}
}
See more on this question at Stackoverflow