Print

Print


Annetta:

Remember that Java is statically typed and while it can be pretty good at
autoboxing, it does have some pitfalls. The error you are getting is pretty
straightforward - you can't cast an Integer to the disaster.Indv type which
makes intuitive sense since you can't cast a primitive to a complex type.
As such, there must be something going on in the code where you are
attempting to do that. Since multiple casting in the same line is typically
bad practice - I've mentored junior developers to avoid it since it makes
your code harder to read and tends to introduce bugs - I suggestion you
break what is going down:

MasonGeometry geometry = (MasonGeometry)object;
Indv indv = (Indv)geometry.getUserData();
int hColor = indv.getHealthStatus();

Generally you should also avoid passing around with java.lang.Object if you
know what type type is. When you have to receive it as a parameter, cast it
immediately and work with the cast object. While this can make the code
more verbose, the compiler is extremely good at optimizing the code so
there is not much to be gained by keeping things short. If you have time
time, you might want to read some of the editorials that were written by
Robert Martin about clean code for some ideas.

Regards,
Robert Zupko

On Thu, Feb 14, 2019 at 10:39 AM Annetta Burger <[log in to unmask]> wrote:

> I like your solution...I didn't think to setUserData() to the agent object
> itself.
>
>                 this.getGeometry().setUserData(this);  -- setting the
> UserData to the agent Indv class object
>
> Unfortunately, I am now getting a casting error in the Portrayal:
>
>                 java.lang.ClassCastException: java.base/java.lang.Integer
> cannot be cast to disaster.Indv
>
> I've tried the casting a number of ways and am getting this same error:
>
>                 int hColor = ((Indv)
> (((MasonGeometry)object).getUserData())).getHealthStatus();  -- original
> suggestion
>                 int hColor = (int) ((Indv)
> ((MasonGeometry)object).getUserData()).getHealthStatus();  -- casting back
> to int
>
> Is there a Java type limitation to get/setUserData()?
>
>
> Another solution to the problem would be to encode the UserData with
> multiple bits of information in a String. I could then break it up in
> decoding methods. It's a little more complex, but it may be more natural to
> the use of get/setUserData()?
>
> Annetta
>