gpt4 book ai didi

java - list.add 覆盖以前的对象

转载 作者:行者123 更新时间:2023-12-02 11:19:34 25 4
gpt4 key购买 nike

我的代码应该将 3 个“位置”类型的对象添加到我在下面声明的“位置”列表中

public class myClass extends JFrame {

static List<Location> locations = new ArrayList<Location>();

这是应该添加到列表中的部分:

locations.add(new Location(new Point(1,1), "Test1", travelLocations.Moon));
locations.add(new Location(new Point(2,2), "Test2", travelLocations.Planet));
locations.add(new Location(new Point(3,3), "Test3", travelLocations.Asteroidfield));

这是我的位置类:

import java.awt.Point;

public class Location {
static Point coordinate;
static String name;
static travelLocations type;

public Location(Point curLoc, String name, travelLocations locType) {
coordinate = curLoc;
locName = name;
type = locType;
}
}

它的作用:它添加名为“Test3”的位置三次,每次我添加一个位置时,它都会添加一个位置并覆盖此列表中的所有已准备好的位置。我知道,它看起来与 Stackoverflow 上的其他问题类似,但我比较了它们并尝试了那些有类似问题的问题,但没有解决方案对我有用。我确信这只是一件小事,并且有一个简单的解决方案,但我看不到它。预先感谢您。

最佳答案

这是因为您将字段声明为静态,这意味着您的类中只有它们的一个副本

关于java - list.add 覆盖以前的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50030608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com