指向hashSet java

时间:2013-04-15 16:37:58

标签: java pointers hashset

我如何编写if语句:如果pos2 [targetPos3]没有指向一个hashset(不是一个hashset)?我试过了,但它仍然给我一个零点异常。

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

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

6 个答案:

答案 0 :(得分:4)

试试这个:

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

由于type erasure,无法查看它是HashSet String(或任何其他类型)。

答案 1 :(得分:1)

instanceof运营商会在这里为您提供帮助。它可以告诉你对象是HashSet,但由于type erasure,在运行时,你将无法判断它是否是HashSet<String>,只是它是HashSet { {1}}。

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

答案 2 :(得分:0)

在Java中使用instanceof operator

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

答案 3 :(得分:0)

instanceof是您正在寻找的运营商:

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

答案 4 :(得分:0)

您想使用instanceof。例如:

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

但是,您还需要实例化数组并进行边界检查。所以:

pos2 = new Object[desiredLength];

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

答案 5 :(得分:0)

您不进行任何错误检查。

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

同时检查word != null 您需要instanceof运营商验证您实际拥有HashSet