如何遍历arraylist以查看是否有任何对象具有相同的值 [英] How to loop through arraylist to see if any objects have the same value

查看:41
本文介绍了如何遍历arraylist以查看是否有任何对象具有相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个汽车的 ArrayList,我想遍历这个数组列表,看看两辆车是否在完全相同的位置,这样我就可以看到它们是否发生了碰撞.我写了以下内容,但我得到的只是没有碰撞",即使它们发生了碰撞.我把它分为两种方法.我的假设是,由于两个循环都从同一点循环,它们是否只是经常一起检查同一辆车或类似的东西?所以 if (i != collided) 每次都被触发?如果是这样,我该如何阻止?

I have an ArrayList of cars, I want to loop through this array list and see if two cars are in the exact same position, so I can see if they have collided. I wrote the following but all I get is 'no collision' even when they have collided. I put it in two methods. My assumption is that since both loops are looping from the same point are they just constantly checking the same car together or something like that? So the if (i != collided) is getting triggered everytime? How do i stop this if so?

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 方法中 -

This is my main class to show how I am calling the method, i use e.check(); in the addcars method -

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();
}
};

更新以包含我的环境类,现在问题很长,但我觉得问题可能在于我如何使用环境类?

Update to include my environment class, the question is quite long winded now but i feel the problem may be in how I am using the environment class?

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"方法添加了以下代码 -

UPDATE - not fixed yet, but i think im getting close. I have added the following code, using the 'nextCar' method -

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

This manages to print out the closest car so i know its somewhat working, though it still wont detect a collision? Any idea what might be the issue? I call this using e.collision() in the addCars method in main

推荐答案

我有方法不能直接解决你的问题,希望能帮到你.

I have method not direct solve your problem, hope can help you.

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

First group,assume you hava a car list:

// 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,那么在同一个位置有车.

if the size of List from group result is not 1,so there car in the same postion。

这篇关于如何遍历arraylist以查看是否有任何对象具有相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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