Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compiler error not making any sense (<identifier> expected)

Tags:

java

casting

I have done a lot of searching for what this compiler error <identifier> expected means, and none of them seem to apply to my situation. Really sorry if this is a duplicate or basic info, but I can't find anything anywhere.

The following code works fine. Note that I am positive myObject1 is indeed a HashSet<String> so the cast is ok.

@SuppressWarnings("unchecked")
HashSet<String> s1 = (HashSet<String>) myObject1;

The following code does NOT work fine. It will compile, but with warnings.

@SuppressWarnings("unchecked")
HashSet<String> s1;
s1 = (HashSet<String>) myObject1;

So then I try the code below.

@SuppressWarnings("unchecked")
HashSet<String> s1;
@SuppressWarnings("unchecked")
s1 = (HashSet<String>) myObject1;

Now it refuses to even compile, giving me the <identifier> expected error that is puzzling me so much. The ^ symbol in my command line is pointing right before the = in the last line. I'm not sure what on earth I could be expected to put BETWEEN the s1 and the =.

Any ideas? Thanks!

like image 631
The111 Avatar asked Oct 14 '12 21:10

The111


1 Answers

You can't apply an annotation to a simple assignment statement. From section 9.7 of the JLS:

Annotations may be used as modifiers in any declaration, whether package (§7.4.1), class (§8.1.1) (including enums (§8.9)), interface (§9.1.1) (including annotation types (§9.6)), field (§8.3.1, §9.3), method (§8.4.3, §9.4), formal parameter (§8.4.1), constructor (§8.8.3), or local variable (§14.4.1).

I agree that the compiler error message could be rather clearer, admittedly...

like image 160
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet