duldi duldi - 9 months ago 37
Java Question

Not an instance of a class Vectors java

I would like to know how to check if an element in a vector is not an instance of a class.
The scenario is if the element in vector m exists in a class we increment sum. If i is not an instance of the class then we return -1. Here is my code:

public static int CountHighs (Vector m) {
int sum=0;
for(int i=0; i<m.size();i++)
{ try{
if(m.get(i) instanceof HighRights)
{ sum+=1;
else if((!m.get(i) instanceof Highrights)||(!m.get(i) instanceof LowRights))
{ sum=-1;
catch(NullPointerException E)
{ System.out.println("Error");
return 0;
return sum;


I have used the operator "!" here for the respondents benefit

The !m.gets causes me an error, I was wondering if there was a way of stating if element is not an instance of this class.


Unary operators (such as !) have a higher precedence than relational operators (such as instanceof) in Java (see the official tutorial for details). So Java tries to interpret !m.get(i) first and fails, since m.get(i) does not return a boolean. In order to solve this issue, you should use parentheses to make the instanceof evaluate first:

else if (!((m.get(i) instanceof Highrights) || (m.get(i) instanceof LowRights))) {