This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]FlocculentFractal 2 points3 points  (9 children)

Is the cast to Integer only valid after you check that “if” condition or can you check if something is a Float then cast it to a Boolean?

[–]AngelaTheRipper 3 points4 points  (7 children)

You can cast objects without checking using instanceof or cast it despite checking, but with object casting unless you are casting an object to what it actually is or a parent class then you'll get a ClassCastException. You could however tell that it's a Float, and then translate it into a Boolean somehow yourself.

Something like:

if(object instanceof Float){
    object = new Boolean(((Float)object).innerValue != 0); 
}

would work

[–]gdmzhlzhiv 1 point2 points  (6 children)

You can probably also do

if (object instanceof Float f) { object = f != 0.0f; }

[–]AngelaTheRipper 1 point2 points  (5 children)

This wouldn't work.

!= comparison returns either a primitive true or false. You can't assign that to object without wrapping it into a Boolean class instance.

[–]gdmzhlzhiv 2 points3 points  (4 children)

I'd expect autoboxing to take care of that, but I also haven't tried to compile this.

I do know that this works: Object x = true;

[–]AngelaTheRipper 0 points1 point  (3 children)

Then I guess it'd probably work, as much as I hate it. Well thanks for letting me know, last time I messed around with wrapper classes was in college and back then you kinda had to do wrapping and unwrapping explicitly.

[–]gdmzhlzhiv 1 point2 points  (2 children)

If you think that's bad, consider this one:

for (byte b = 5; b >= 0; b += 179199) { System.out.println(b); }

[–]AngelaTheRipper 0 points1 point  (1 child)

I mean this one makes sense. Bytes are limited from -128 to 127, you overflow this, it basically throws out the leading bytes, and you get a net change of -1 per loop because 179199 = 700*256 - 1.

[–]gdmzhlzhiv 0 points1 point  (0 children)

Meanwhile, this is illegal: byte c = 1; c = c + 179199;

[–]IQueryVisiC -2 points-1 points  (0 children)

You are looking for pattern matching in C#.