2

How would I write an if statement that says: if pos2[targetPos3] doesn't point to a hashset (is not a hashset) ? I tried that but it still gives me a null point exception.

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

if(pos2[targetPos3] != (HashSet<String>) pos2[targetPos3]){
   System.out.println("Sorry");
 }
Dodi
  • 1,812
  • 3
  • 22
  • 36
  • 1
    Check for null using `pos2[index] == null` and use `instanceof` to check for type if not null. Why are you storing them in `Object[]` anyway ? – Deepak Bala Apr 15 '13 at 16:39
  • 1
    [SSCCE please](http://sscce.org). – Matt Ball Apr 15 '13 at 16:39
  • @DeepakBala, you do not need to check that `pos2[idx]` is null when checking for `instanceof` is is null then can not be a instance of naturally. – Damian Leszczyński - Vash Apr 15 '13 at 16:44
  • @Vash while you're right, it does not invalidate the comment. No one knows that the OP is trying to do. `targetPos3 = word.charAt(2) - 'a';` does not make sense. What is `word` ? What is this snippet even supposed to do !? – Deepak Bala Apr 15 '13 at 16:49
  • @DeepakBala, I was just referring that, validating null before a instance check is redundant (and also recognized as bad practice). The snipes, IMHO present the problem that was highly recognized looking on the answers. what `word` is and the logic of code is quite irrelevant at this point. – Damian Leszczyński - Vash Apr 15 '13 at 16:52

6 Answers6

4

Try this:

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

There is no way to see if it's a HashSet of String (or any other type for that matter) because of type erasure.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
1

The instanceof operator will help you here. It can tell you if the object is a HashSet, but due to type erasure, here at runtime, you won't be able to tell if it's a HashSet<String>, just if it's a HashSet.

if (!(pos2[targetPos3] instanceof HashSet)) {
rgettman
  • 167,281
  • 27
  • 248
  • 326
0

Use instanceof operator in Java.

if (!(pos2[targetPos3] instanceof HashSet)) {
   // ...
}
anubhava
  • 664,788
  • 59
  • 469
  • 547
0

instanceof is the operator you're looking for:

if(! pos2[targetPos3] instanceof HashSet){
    System.out.println("Sorry");
}
PaulProgrammer
  • 13,123
  • 3
  • 29
  • 49
0

You want to use instanceof. For example:

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

However you also need to instantiate your array and do bounds checking. So:

pos2 = new Object[desiredLength];

if((targetPos3 < pos2.length) && (pos2[targetPos3] instanceof HashSet)) {
    ...
}
Rob Watts
  • 6,260
  • 2
  • 31
  • 57
0

You don't do any error checking.

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

Check also for word != null.
What you need is instanceof operator to verify is you actually have a HashSet

Cratylus
  • 49,824
  • 60
  • 195
  • 327