Java如何检查数组列表中的对象是否包含某个值

标签 java arraylist

您好,我有一个程序,您可以放置​​瓷砖来 build 房屋,然后出售房屋。我只想出售房屋,前提是建筑物有一扇门和至少一扇 window 。 我的数组列表如下所示:

   public static ArrayList<block> b = new ArrayList<block>();

每种类型的图 block 都有一个 ID。门瓷砖为 1, window 瓷砖为 2,墙瓷砖为 3。

for(int i = 0; i < play.b.toArray().length;i++){
    if(play.b.contains(play.b.get(i).id == 1)){
        cansell= true;
    }else{
        cansell= false;
    }

}

如何检查数组列表中的对象是否包含特定值,在本例中为值 1。

这是门类:

public class door extends block{


    public cockpit(int x,int y,int rot){
        this.x = x;
        this.y = y;
        this.rotate = rot;
        r = new Rectangle(x - (int)play.camx,y - (int)play.camy,20,20);
        id = 3;
    }

    public void tick(){
        createCollisionRect();

        if(Comp.mr && r.contains(new Point((Comp.mx ) ,(Comp.my) ))){
            remove = true;

        }
        if(remove){
            //play.gui.money +=800;

        }

    }

    public void render(Graphics g){
        Graphics2D g2 = (Graphics2D) g;

        if (rotate == 0) {
            ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
            img = i62.getImage();
            g.drawImage(img, x - (int) play.camx, y - (int) play.camy,20,20, null);
        }
        if (rotate == 1) {
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.toRadians(90),10,10);

            ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
            img = i62.getImage();

            g2.drawImage(img,at, null);
        }
        if (rotate == 2) {
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.toRadians(180),10,10);

            ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
            img = i62.getImage();

            g2.drawImage(img, at, null);
        }
        if (rotate == 3) {
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.rotate(Math.toRadians(-90),10,10);

            ImageIcon i62 = new ImageIcon("res/tiles/cockpit.png");
            img = i62.getImage();

            g2.drawImage(img, at, null);

        }


    }
}

最佳答案

这看起来很简单。

请注意,无需获取“id”...ArrayList 本身存储值。

您只需检查数组中的索引位置值是否包含您要查找的值:

for(int i = 0; i < play.b.toArray().length;i++){
    String valueID = play.b.get(i);
    if(valueID.contains("1")){
        cansell= true;
    }else{
        cansell= false;
    }
}
<小时/>

这应该可以回答你的问题,如果没有,这确实有帮助:JArrayLists

希望这能回答您的问题。

让我知道结果

关于Java如何检查数组列表中的对象是否包含某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29733231/

相关文章:

java - 如何获取并按空格分割输入的多个字符串行,然后将它们添加到Java中的arrayList?

Python列表中的列表操作

java - 查找两个字符串中不同的字符

java - 如何使用reverse方法反转ArrayList的所有元素?

Java: "long"数字占用多少内存?

java - ListView 在 android 中不起作用

java - 为什么我会收到 nullPointerException

Javascript:循环数组中的项目

java - web.xml 安全约束配置不考虑 URL 查询字符串

java - JBullet - 静态时凸形状无法正常工作