[英]Java how to check if an object in an arraylist contains a certain value
您好,我有一个程序,您在其中放置砖块来建造房屋,然后出售房屋。 我只想在房屋有门和至少一个窗户的情况下出售房屋。 我的数组列表看起来像这样:
public static ArrayList<block> b = new ArrayList<block>();
每种类型的图块都有一个ID。 门磁砖为1,窗户磁砖为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
希望这能回答您的问题。
让我知道结果
if(play.b.contains(play.b.get(i).id == 1)){
计算结果类似于if(play.b.contains(true)){
(或分别为false)。 因此,由于您在ArrayList
具有int
,因此应更改以下代码:
cansell = play.b.contains(1);
而是整个循环。
根据评论中的更新:
public void canSell () {
cansell = play.b.contains(1) && play.b.contains(2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.