我无法弄清楚为什么我的集合在某些时候是空的

时间:2013-10-06 19:50:50

标签: java

我正在将DVD添加到收藏中。我每次添加DVD时都会尝试对其进行排序。我一直收到错误消息:

Exception in thread "main" java.lang.NullPointerException
    at DVDCollection.addDVD(DVDCollection.java:44)

你们能告诉我如何解决这个问题吗?

    public void addDVD (String title, String director, int year,
  double cost, boolean bluray)
   {
    if (count == collection.length)
    increaseSize();
    collection[count] = new DVD (title, director, year, cost, bluray);
    totalCost += cost;
    count++;

    if (count > 0)
    {
        int min;
        for (int i = 0; i < collection.length - 1; i++)
        {
            min = i;
            for (int j = i + 1; j < collection.length; j ++)
            {
               if(collection[j].getDirector().compareTo(collection[i].getDirector()) <   0)
               min = j;

               temp[min] = collection[min];
               collection[min] = collection[j];
               collection[j] = temp[min];
            }
        }
    }


}
public class Movies
 {
    //-----------------------------------------------------------------
    // Creates a DVDCollection object and adds some DVDs to it. Prints
        // reports on the status of the movies.
     //-----------------------------------------------------------------
public static void main (String[] args)
{
    DVDCollection movies = new DVDCollection();
    movies.addDVD ("The Godfather", "Francis Ford Coppola", 1972, 24.95, true);
    movies.addDVD ("District 9", "Neill Blomkamp", 2009, 19.95, false);
    movies.addDVD ("Iron Man", "Jon Favreau", 2008, 15.95, false);
    movies.addDVD ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false);
    movies.addDVD ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true);
    System.out.println (movies);
    movies.addDVD ("Iron Man 2", "Jon Favreau", 2010, 22.99, false);
    movies.addDVD ("Casablanca", "Michael Curtiz", 1942, 19.95, false);
    System.out.println (movies);



    System.out.println(movies);

     }
   }

1 个答案:

答案 0 :(得分:1)

Java带来了许多方便的库。 您不必重新发明轮子并手动分拣(学习除外)。

因此,让您的 DVD 实施可比较并进行基于导演的比较,然后使用TreeSet

这是一个使用树结构保持元素按其自然顺序排序的集合:在每次插入时对集合进行排序的效率要高得多。