2013-04-15 87 views
2

我該如何編寫一條if語句:如果pos2 [targetPos3]沒有指向哈希集(不是哈希集)?我嘗試過,但它仍然給我一個零點例外。指向哈希集java

Object[] pos2; 
int targetPos3; 
targetPos3 = word.charAt(2) - 'a'; 

if(pos2[targetPos3] != (HashSet<String>) pos2[targetPos3]){ 
    System.out.println("Sorry"); 
} 
+1

檢查NULL使用'POS2 [指數] == null'和使用'instanceof'如果不爲null檢查的類型。爲什麼你將它們存儲在Object []中? –

+1

[SSCCE請](http://sscce.org)。 –

+0

@DeepakBala,當檢查'instanceof'爲null時不需要檢查'pos2 [idx]'爲空,那麼它就不能是一個自然的實例。 –

回答

4

試試這個:

if(!(pos2[targetPos3] instanceof HashSet)){ 
    System.out.println("Sorry"); 
} 

沒有辦法,看看它是一個StringHashSet(或任何其他類型的這個問題),因爲type erasure

+0

謝謝! – Dodi

1

instanceof運營商將在這裏爲您提供幫助。它可以告訴你,如果對象是HashSet,但由於type erasure,在運行時,您將無法判斷它是否爲HashSet<String>,如果它是HashSet

if (!(pos2[targetPos3] instanceof HashSet)) { 
0

instanceof是你要找的操作:您要使用instanceof

if(! pos2[targetPos3] instanceof HashSet){ 
    System.out.println("Sorry"); 
} 
0

。例如:

if(pos2[targetPos3] instanceof HashSet) { 
    ... 
} 

但是,您還需要實例化您的數組並進行邊界檢查。所以:

pos2 = new Object[desiredLength]; 

if((targetPos3 < pos2.length) && (pos2[targetPos3] instanceof HashSet)) { 
    ... 
} 
0

你不做任何錯誤檢查。

if(targetPos3 < pos2.length){ 
    if(!(pos2[targetPos3] instanceof HashSet)){ 
     System.out.println("Sorry"); 
    } 
} 

還請檢查word != null
你需要的是instanceof運營商能夠驗證是你確實有一個HashSet