且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

引用Java列表始终返回最后一个元素

更新时间:2023-11-09 23:48:10

您需要检查Sprite类的hashcodeequals实现.他们需要考虑Sprite的相关字段,因此两个不同的字段不会返回相同的哈希码或等于true的true.我认为如果您使用默认实现(例如不覆盖它),它可以工作,但是请确保实现一个.在eclipse中,您可以选择SourceGenerate hashCode() and equals().不过,如果您确实使用ArrayList,则这无关紧要(我在您的代码中看不到).

You need to check the hashcode and equals implementation of your Sprite class. They need to consider the relevant fields of Spriteso two different ones don't return the same hashcode or return true for equals. I think it works if you're using the default implementation (e.g. not overriding it), but implement one to be sure. In eclipse you can choose SourceGenerate hashCode() and equals(). This should not matter though if you're really using ArrayList (I don't see that in your code).

我同意@Sanket的观点,这可能是将浮点数转换为整数的问题.也许看起来您每次都得到同一个?

I agree with @Sanket that it may be a problem of converting a floating point number to integer. Maybe it just looks like you're getting the same one every time?

此外,您应该使用Java 5的enhanced for-loop.第二个循环可以像这样重写(甚至可以按预期工作……):

Also, you should use the enhanced for-loop of Java 5. The second loop could be rewritten like this (and may even work as expected then...):

int x = 0;
for (Sprite spr : gSprite){
    System.out.println("Ball: " + x + " X: " + spr.getX()+ " Y: " + spr.getY() + " vX: " + spr.getvX() + " vY: " + spr.getvY() + " Color: " + spr.getColor().toString());
    x++;
}

最后但并非最不重要的一点是,您应该真正使用switch/case而不是四个ifs.这实际上不会解决您的问题,但这只是不好的风格.看看:

And, last but not least, you should really use switch/case instead of the four ifs. This actually won't help your problem but it's just bad style. Take a look:

switch (colorValue) {
        case 0:
            color = Color.BLUE;
            break;
        case 1:
            color = Color.RED;
            break;
        case 2:
            color = Color.YELLOW;
            break;
        case 3:
            color = Color.GREEN;
            break;
        default:
            throw new RuntimeException("Unexpected color!");
}

顺便说一句:对于这种模式,还有其他方法,例如使用EnumMap.我只是认为使用switch/case对于一个逻辑位有2个以上ifs.当然,默认情况处理不当,需要完善.

Btw: There are other approaches like using Enum or a Map for this kind of pattern. I just think having more than 2 ifs for one logic-bit merits using switch/case. Of course, the default case is handled poorly and would need refinement.

哦,还有一件事:您应该真正编写方法名称为小写/驼峰式.基本上,每个Java程序员都采用这种方式.

Oh and one more thing: You should really write method names lowercase/camel case. Basically every Java programmer excepts it this way.