Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Integer in Switch Statement
    text
    copied!<p>For various business reasons I want to hold some static IDs in one of my classes. They were originally <code>int</code> but I wanted to change them to <code>Integer</code> so I could do an equals on them (ie <code>MY_ID.equals(..)</code> which avoids NPEs)</p> <p>When I change them to Integer I get errors in my switch statement. The <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html" rel="noreferrer">docs</a> say that Integer should be ok within Switches. </p> <p>To quote </p> <blockquote> <p>[Switch] also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).</p> </blockquote> <p>In my code below if i is a <code>int</code> then it compiles. When it is an <code>Integer</code> it doesnt saying that a <code>constant expression is required</code>. I have tried doing <code>.intValue()</code> but this doesnt work either.</p> <p>Am I being really stupid? Or completely misreading the <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html" rel="noreferrer">docs</a>?</p> <pre><code>private static final Integer i = 1; @Test public void test() { switch(mObj.getId()){ case i: //do something default: //do something default } } </code></pre> <p>Thanks for any pointers here. For the time being I am keeping them as <code>int</code> and doing <code>new Integer(myint).equals(...)</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload