0

我正在将 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);

     }
   }
4

1 回答 1

1

Java 提供了很多方便的库。您不必重新发明轮子并手动进行分类(学习除外)。

因此,使您的DVD实现Comparable与基于导演的比较,然后使用TreeSet

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

于 2013-10-06T20:05:24.957 回答