![](/img/trans.png)
[英]Search through an ArrayList of Objects that have a value of an attribute within a certain range
[英]How to loop through arraylist to see if any objects have the same value
我有一個汽車的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()來稱呼它
您check()
在cars
每輛汽車上調用check()
? 您發布的代碼未顯示如何使用check()
。
另外,你寫了
兩輛車完全在同一位置
但是必須提醒您,使用浮點位置確實很棘手。 如果兩輛汽車具有相同的初始位置,並且以相同的elapsed
參數對它們調用了速度和tick
,那么它們將具有相同的position
。 但是,在任何其他情況下,由於舍入誤差,它們的位置可能相距很小,例如0.00000000001
。
您必須向我們展示一個完整的示例,其中包含一組汽車以及如何調用它們的check()
。
該位置是一個雙精度值,因此位置不能完全相同。 因此定義一個最小距離值,並在該值以下考慮碰撞,例如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;
}
}
我有方法不能直接解決您的問題,希望能對您有所幫助。
第一組,假設您有汽車清單:
// 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());
}
}));
其次檢查組數結果:
如果分組結果列表的大小不為1,則同一位置有汽車。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.