Java 返回ArrayList类型的null

Java 返回ArrayList类型的null,java,Java,我有一个小问题。。如何返回数组列表类型的null。。下面是完整的问题:RectangleList类管理一个矩形列表。它有一个以矩形数组列表为参数的构造函数。它有一个方法返回面积最小的矩形(如果列表为空,则返回null)。 谢谢大家! 以下是我所做工作的代码: public Rectangle smallestArea() { double min = list.get(0).getWidth() * list.get(0).getHeight();

我有一个小问题。。如何返回数组列表类型的null。。下面是完整的问题:RectangleList类管理一个矩形列表。它有一个以矩形数组列表为参数的构造函数。它有一个方法返回面积最小的矩形(如果列表为空,则返回null)。 谢谢大家!

以下是我所做工作的代码:

public Rectangle smallestArea()
            {
            double min = list.get(0).getWidth() * list.get(0).getHeight();
            int k=0;

           if(list.size() > 0)
           {
            for(int i=0; i<list.size(); i++)
                {

                if(list.get(i).getWidth() * list.get(i).getHeight() < min)
                {
                    min = list.get(i).getWidth() * list.get(i).getHeight();
                    k=i;}
                }

             return list.get(k);
           }

           else
               {
               return null;
               }
    }

    And I get this error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.rangeCheck(ArrayList.java:604)
        at java.util.ArrayList.get(ArrayList.java:382)
        at RectangleList.smallestArea(RectangleList.java:39)
        at RectangleListTester.main(RectangleListTester.java:25)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at com.horstmann.codecheck.Main$2.run(Main.java:249)
    Error:

    Program exited before all expected values were printed.
public矩形smallestrea()
{
double min=list.get(0.getWidth()*list.get(0.getHeight();
int k=0;
如果(list.size()>0)
{

对于(int i=0;i您可以在需要时返回null。您返回的是对对象的引用,null是对不存在的对象的通用引用,因此您不必强制转换它或任何东西

public Rectangle getSmallestAreaRectangle() {
    if (theList.isEmpty()) {
        return null;
    }

    // ... do computations

    return theRectangle;
}

null
不属于任何类型,可以用于任何类型(不包括原语)

因此,您可以总是说
MyClass obj=null;

另一个问题可能是,如果您有两个具有不同参数类型的重载方法,例如:

void foo(String s);
void foo(Integer i);
在这种情况下,尝试调用:
foo(null)
将产生编译错误,因为编译器无法理解您所指的两种方法中的哪一种。在这种情况下,您可以执行强制转换:

  • foo((String)null)
    将调用
    foo()的第一个版本
  • foo((整数)null)
    将调用第二个版本的
    foo()

为什么不直接返回null?你能添加更多信息吗?只需返回
null
。没有
ArrayList
类型的“
null
”。返回null;//就这么简单…-1因为很明显,你在发布问题之前没有尝试过任何东西。做别人的作业是作弊;)有时我不知道这是家庭作业还是一个迷失在编程概念中的新程序员:pOne point for you;)但想象一下,如果这是一个专业人士在工作:我会为他的公司担心^^^谢谢你的回答!:)