引用Java列表始终返回最后一个元素 [英] Referencing a java list always returns the last element

查看:85
本文介绍了引用Java列表始终返回最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑,需要另一双眼睛看一下.该代码正常工作,突然停止工作.基本上,我是将对象添加到arraylist.在构建列表时,我会看到它,并且似乎在每次迭代中都添加了一个唯一的对象.基本上是一个精灵,它将显示在屏幕上及其x,y坐标,颜色和速度.之前的工作原理是,精灵显示在屏幕上,现在看起来好像复制了添加到列表中的最后一个对象,X多次运行循环,最终得到相同的对象.这没有任何意义...

I'm stumped and need another pair of eyes to look at this. This code was working and suddenly stopped working. Basically I'm adding an object to an arraylist. when I'm building the list I watch it and it seems to add a unique object each iteration. Basically a sprite that will appear on the screen and its x, y coordinates, color, and speed. Earlier this worked and the sprites would appear scattered on screen, now it seems to duplicate the very last object added to the list, X number of times I run the loop I end up with the same object. which doesn't make any sense...

第一个println语句打印将传递给构造函数的内容.因此它按原样打印出来.

The first println statements prints whats being passed to the constructor. So it prints out as so.

球:1 x:123 y:344颜色:蓝色 球:2 x:3 y 233颜色:绿色 球3 x:24 y:3颜色:蓝色

Ball: 1 x: 123 y:344 Color: Blue Ball: 2 x: 3 y 233 Color: Green Ball 3 x: 24 y: 3 Color: Blue

到目前为止,一切看起来都很不错.然后,我实际上将列表打印到控制台,然后得到

Everything looks great so far. Then I actually print the list to console and I get

球:1 x:24年:3颜色:蓝色 球:1 x:24年:3颜色:蓝色 球:1 x:24年:3颜色:蓝色

Ball: 1 x: 24 y: 3 Color: Blue Ball: 1 x: 24 y: 3 Color: Blue Ball: 1 x: 24 y: 3 Color: Blue

这是我要找出原因的原因所在...

Which here in lies the problem I'm trying to figure out why that is happening...

  //When I create the List Eclipse refused to accept it until I initialized it like so...

  java.util.List <Sprite> sprite = new java.util.ArrayList<Sprite>();    
  //yes I did import java.util.*; Eclipse still was digging it. This was working correctly despite the way i added it. I also changed this to a Vector which Eclispe was more content with with no effect. 

  private void GenerateSprites(){
        //Random to keep it random
        Random r = new Random(System.currentTimeMillis());
        //variables for selecting and setting color
        Color color = null;
    int colorValue;
    //variables for their x,y coordinates
    float bX = 0;
    float bY = 0;
    //Create each ball set the color and generate the x,y coordinates
    for (int x = 0; x < NUM_BALLS; x++){
        colorValue = r.nextInt(4);
        if (colorValue == 0) color = Color.BLUE;
        if (colorValue == 1) color = Color.RED;
        if (colorValue == 2) color = Color.YELLOW;
        if (colorValue == 3) color = Color.GREEN;

        bX = r.nextInt((int)(gameField.getWidth() - gameField.getWidth() / 4)+SCRN_MARGIN);
        bY = r.nextInt((int)(gameField.getHeight() - gameField.getHeight() / 4)+SCRN_MARGIN);

        //place the new ball in the gameField
   //print the values being passed to the sprite constrcutor for debug purposes. The out put of this line indicates that all is well at this point.             
System.out.println("Ball: " + x + " X: " + bX+ " Y: " + (bY+SCRN_MARGIN) + " Color: " + color.toString());
        gSprite.add(new Sprite((float)bX, (float)bY+SCRN_MARGIN, BALL_SIZE, color));

    }
    //Now that the sprites are added to this list print out the list.   When this line executes it shows a list of NUM_BALLS all of which have the exact sdame vlaues as the last sprite added earlier. 
    for (int x = 0; x < gSprite.size(); x++){
        Sprite spr = gSprite.get(x);

  System.out.println("Ball: " + x + " X: " + spr.getX()+ " Y: " + spr.getY() + " vX: " + spr.getvX() + " vY: " + spr.getvY() + " Color: " + spr.getColor().toString());
    }

}

推荐答案

您需要检查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.

这篇关于引用Java列表始终返回最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆