如何遍历arraylist以查看是否有任何对象具有相同的值

时间:2019-01-13 16:43:52

标签: java loops for-loop arraylist

我有一个汽车的ArrayList,我想遍历这个数组列表,看看两辆汽车是否在完全相同的位置,这样我就可以看到它们是否发生碰撞。我写了以下内容,但即使它们发生碰撞,我得到的只是“没有碰撞”。我把它放在两种方法中。我的假设是,由于两个循环都从同一点开始循环,是它们只是不断地一起检查同一辆车还是类似的东西?因此,是否每次都触发if(i!=碰撞)?如果是这样,我该如何阻止?

public void carCollision(Car collided) {

    for (Car i: cars) {
        if(i != collided && i.getLane() == collided.getLane() && 
            i.getPosition() == collided.getPosition()) {
            System.out.println("collision");
        } else {
            System.out.println("no collisions");
        }
    }
}

public void check() {
    for (Car a: cars) {
        carCollision(a);
    }
}

汽车课-

/** State of a car on the road */
public class Car {

/** Position of this car on the road (i.e. how far down the road it is) in pixels */
private double position;
/** Current speed in pixels per second */
private double speed;
/** Lane that this car is on */
private int lane;
/** Colour of this car's display */
private Color color;

public Car(double position, double speed, int lane, Color color) {
    this.position = position;
    this.speed = speed;
    this.lane = lane;
    this.color = color;
}

/** @return a new Car object with the same state as this one */
public Car clone() {
    return new Car(position, speed, lane, color);
}

/** Update this car after `elapsed' seconds have passed */
public void tick(Environment environment, double elapsed) {
    position += speed * elapsed;
}

public double getPosition() {
    return position;
}

public int getLane() {
    return lane;
}

public Color getColor() {
    return color;
}

这是我的主要课程,展示了我如何调用该方法,我使用e.check();。在addcars方法中-

public class Main extends Application {
public static void main(String[] args) {
    launch(args);
}

public void start(Stage stage) {

    final Environment environment = new Environment();
    final Display display = new Display(environment);
    environment.setDisplay(display);

    VBox box = new VBox();

    stage.setTitle("Traffic");
    stage.setScene(new Scene(box, 800, 600));

    HBox controls = new HBox();
    Button restart = new Button("Restart");
    controls.getChildren().addAll(restart);
    box.getChildren().add(controls);

    restart.setOnMouseClicked(e -> {
            environment.clear();
            display.reset();
            addCars(environment);
        });

    box.getChildren().add(display);

    addCars(environment);

    stage.show();
}

/** Add the required cars to an environment.
 *  @param e Environment to use.
 */
private static void addCars(Environment e) {
    /* Add an `interesting' set of cars */
    Random r = new Random();
    e.add(new Car(  0, 63, 2, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car( 48, 79, 0, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(144, 60, 0, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(192, 74, 0, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(240, 12, 1, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(288, 77, 0, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(336, 28, 1, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(384, 32, 2, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.add(new Car(432, 16, 1, new Color(r.nextFloat(), r.nextFloat(), r.nextFloat(), 1.0)));
    e.check();
}
};

更新为包括我的环境类,现在这个问题已经解决了很长时间,但是我觉得问题可能出在我如何使用环境类上?

public class Environment implements Cloneable {

/** All the cars that are on our road */
private ArrayList<Car> cars = new ArrayList<Car>();
/** The Display object that we are working with */
private Display display;
/** Number of lanes to have on the road */
private int lanes = 4;
private long last;

/** Set the Display object that we are working with.
 */
public void setDisplay(Display display) {
    this.display = display;

    /* Start a timer to update things */
    new AnimationTimer() {
        public void handle(long now) {
            if (last == 0) {
                last = now;
            }

            /* Update the model */
            tick((now - last) * 1e-9);

            /* Update the view */
            double furthest = 0;
            for (Car i: cars) {
                if (i.getPosition() > furthest) {
                    furthest = i.getPosition();
                }
            }
            display.setEnd((int) furthest);
            display.draw();
            last = now;
        }
    }.start();
}

/** Return a copy of this environment */
public Environment clone() {
    Environment c = new Environment();
    for (Car i: cars) {
        c.cars.add(i.clone());
    }
    return c;
}

/** Draw the current state of the environment on our display */
public void draw() {
    for (Car i: cars) {
        display.car((int) i.getPosition(), i.getLane(), i.getColor());
    }
}

/** Add a car to the environment.
 *  @param car Car to add.
 */
public void add(Car car) {
    cars.add(car);
}

public void clear() {
    cars.clear();
}

/** @return length of each car (in pixels) */
public double carLength() {
    return 40;
}

/** Update the state of the environment after some short time has passed */
private void tick(double elapsed) {
    Environment before = Environment.this.clone();
    for (Car i: cars) {
        i.tick(before, elapsed);
    }
}

/** @param behind A car.
 *  @return The next car in front of @ref behind in the same lane, or null if there is nothing in front on the same lane.
 */
public Car nextCar(Car behind) {
    Car closest = null;
    for (Car i: cars) {
        if (i != behind && i.getLane() == behind.getLane() && i.getPosition() > behind.getPosition() && (closest == null || i.getPosition() < closest.getPosition())) {
            closest = i;
        }
    }
    return closest;
}

public void carCollision(Car collided) {

    for (Car i: cars) {
        double MIN_DIS = 0.1;
        if(!(i.equals(collided)) && i.getLane() == collided.getLane() && 
            (Math.abs(i.getPosition() - collided.getPosition()) < MIN_DIS )) {
            System.out.println("collision");
        } else {
            System.out.println("no collisions");
        }
    }
}

public void check() {
    for (Car a: cars) {
        carCollision(a);
    }

}

public void speed() {
    for (Car a : cars) {
        a.setSpeed();
    }
}

/** @return Number of lanes */
public int getLanes() {
    return lanes;
}

}

更新-尚未修复,但我想我越来越近了。我使用“ nextCar”方法添加了以下代码-

public Car nextCar(Car behind) {
    Car closest = null;
    for (Car i: cars) {
        if (i != behind && i.getLane() == behind.getLane() && i.getPosition() > behind.getPosition() && (closest == null || i.getPosition() < closest.getPosition())) {
            closest = i;
        }
    }
    return closest;
}

public void collision() {
    Environment e = Environment.this.clone();
    double MIN_DIS = 0.5;
    for (Car i : cars) {
        e.nextCar(i);
        for (Car a : cars) {
            if(!(i.equals(a)) && i.getLane() == a.getLane() && 
                (Math.abs(i.getPosition() - a.getPosition()) < MIN_DIS)) {
            System.out.println("collision");
        } else {
            System.out.println("no collision");
        }

            System.out.println("closest car is" + i);
        }
    }
}

这设法打印出最近的汽车,所以我知道它在某种程度上可以工作,尽管它仍然不会检测到碰撞?知道可能是什么问题吗?我在main的addCars方法中使用e.collision()来调用它

3 个答案:

答案 0 :(得分:0)

您是否在check()中的每辆车上调用cars?您发布的代码未显示您如何使用check()

另外,你写了

  

两辆车的位置完全相同

但是必须提醒您使用浮点位置,这确实很棘手。如果两辆汽车具有相同的初始位置,速度和tick,并且它们使用相同的elapsed参数,则它们将具有相同的position。但是,在任何其他情况下,由于舍入误差,它们的位置可能相距很小,例如0.00000000001

您必须向我们展示带有一组汽车的完整示例,以及如何在它们上调用check()

答案 1 :(得分:0)

位置是双精度值,因此位置不能完全相同。因此,请定义一个最小距离值,并在该值以下考虑冲突,例如MIN_DIS = 0.1

public void carCollision(Car collided) {

    for (Car i: cars) {
        if(!(i.equals(collided)) && i.getLane() == collided.getLane() && 
            (Math.abs(i.getPosition() - collided.getPosition()) < MIN_DIS)) {
            System.out.println("collision");
        } else {
            System.out.println("no collisions");
        }
    }
}

public void check() {
    for (Car a: cars) {
        carCollision(a);
    }
}

还有您的汽车课程。

import java.awt.Color;
import org.omg.CORBA.Environment;

/** State of a car on the road */
public class Car {

    /**
     * Position of this car on the road (i.e. how far down the road it is) in
     * pixels
     */
    private double position;
    /** Current speed in pixels per second */
    private double speed;
    /** Lane that this car is on */
    private int lane;
    /** Colour of this car's display */
    private Color color;

    public Car(double position, double speed, int lane, Color color) {
        this.position = position;
        this.speed = speed;
        this.lane = lane;
        this.color = color;
    }

    /** @return a new Car object with the same state as this one */
    public Car clone() {
        return new Car(position, speed, lane, color);
    }

    /** Update this car after `elapsed' seconds have passed */
    public void tick(Environment environment, double elapsed) {
        position += speed * elapsed;
    }

    public double getPosition() {
        return position;
    }

    public int getLane() {
        return lane;
    }

    public Color getColor() {
        return color;
    }

    public double getSpeed() {
        return speed;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Car){
            Car car = (Car) obj;
            return car.getPosition() == this.position && car.getLane() == this.lane && car.getColor().equals(this.color) && car.getSpeed() == this.speed; 
        }
        return false;
    }
}

答案 2 :(得分:0)

我有方法不能直接解决您的问题,希望能为您提供帮助。

第一组,假设您有汽车清单:

// init the cars
List<Car> cars = new ArrayList<>();

// first group
Map<Tuple2<Double,Integer>,List<Car>> groupResult = cars.stream()
    .collect(Collectors.groupingBy(new Function<Car, Tuple2<Double,Integer>>() {
        @Override
        public Tuple2<Double, Integer> apply(Car car) {
            return new Tuple2<>(car.getPosition(),car.getLane());
        }
    }));

第二次检查分组结果的数量:

如果分组结果中List的大小不为1,则同一位置有汽车。