2017-01-04 27 views
-1

爲什麼不編譯?我正在嘗試按照int屬性:courseLevel的升序對學校課程列表進行排序。修復我的排序錯誤

我有一個類名爲UCFCourse與幾個對象courses[]。我分配屬性值的每個對象而遞增x.Here是我在我的主要代碼:

courses[x] = new UCFCourse(courseCode, courseLevel, courseHours, replaceString, eitherCourse); 

這是我加我courses[]。如果我打印出來ListOne我得到包含我的所有課程大規模列表。

List<UCFCourse> ListOne = new ArrayList<UCFCourse>(); 
     for (int i = 0; i < courses.length; i++) { 
      ListOne.add(courses[i]); 
     } 


//I added all my courses[] to a List 
List<UCFCourse> ListOne = new ArrayList<UCFCourse>(); 
Collections.sort(ListOne, new CourseComparator()); 

比較類:

import java.util.Comparator; 

public class CourseComparator implements Comparator<UCFCourse> { 
    public int compare(UCFCourse Course1, UCFCourse Course2) { 
     return Course1.getCourseLevel() - Course2.getCourseLevel(); 
    } 
} 

當我最初創建我的對象時,它看起來像這樣:

UCFCourse[] courses = new UCFCourse[75]; 

不知道這一點是相關的,因爲我加入他們都成已經有數組列表,但我想徹底。

錯誤:

Exception in thread "main" java.lang.NullPointerException 
+0

你'null'-S在'ListOne'列表valiable。檢查你添加它們的位置。 –

+1

您已發佈運行時錯誤,而不是編譯錯誤。 – shmosel

+2

你是否使用'int'或'Integer'作爲'getCourseLevel()'的返回值? –

回答

1
List<UCFCourse> ListOne = new ArrayList<UCFCourse>(); 
<add your items to list here> 
Collections.sort(ListOne, new CourseComparator()); 

因爲這些代碼代表,你發送一個空白列表的比較。如果您確定列表中有項目,請檢查傳遞的課程1和課程2項目是否有實際價值。您可以快速測試'getCourseLevel()',並將值返回給調用方法。

+0

OP表示從數組中填充了「ListOne」。假設數組中有空值,試圖調用'getCourseLevel()'將拋出相同的異常。 – shmosel

1

你只是在你的ListOne變量上創建一個新的對象,該變量仍然是空的,這就是爲什麼你會得到一個NullPointerException。

並嘗試使用駱駝案例,以便您可以正確識別您的代碼。

+0

我有一個for循環添加objects.I編輯它。 – OneU

1

從代碼片段您提供我可以告訴你以下幾點:

UCFCourse[] courses = new UCFCourse[75]; 

只創建一個數組,充滿對象。遍歷這個數組並添加每個對象到你的ArrayList中都不會實例化它們。

List<UCFCourse> ListOne = new ArrayList<UCFCourse>(); 
    for (int i = 0; i < courses.length; i++) { 
     ListOne.add(courses[i]); 
    } 

的後果是,該方法Comparator#compare(UCFCourse c1, UCFCourse c2)參數,c1和c2,將爲空,這導致了空指針異常。

你需要將它們添加到ArrayList之前做的是創造你的UCFCourse對象,例如:

 for (int i = 0; i < courses.length; i++) { 
      courses[i] = new UCFCourse(...); 
     } 
+0

我更新了我的帖子。謝謝! – OneU

+0

@Mrmug你還在** **相同​​的NPE嗎?我在eclipse中試過這個問題,在初始化對象後,NPE消失了。 – crazyExplorer