Java Vector/List 删除元素

Java Vector/List Element Removal

您好,我有 2 个关于 Java 矢量元素删除的快速问题。

  1. 如何从矢量中删除元素
  2. 如果我从我的对象中的向量中删除一个元素,然后我将我的对象 GSON 到一个 JSON 文件,该元素是否会从 json 文件中消失?或者删除的元素是否仍然在 json 文件中?

这是代码:

public class Activities {
    private String instanceID;
    private String tripID;
    public List<ActivitySensor> acts;
    private String gout;

    public Activities() {
        acts = new Vector<ActivitySensor>(3, 3);
    }
    // etc
    // etc
}

public class ActivitySensor {
    private String name;
    private int typeID;
    private int confidence;
    private Date beginTime;
    // etc
    // etc
}

我实例化如下:

ActivitySensor act;
Activities activities = new Activities();
act = new ActivitySensor();

然后,当我想要将一组新元素添加到 ActivitySensor 时,我会这样做...

activities.acts.add(act);

以上所有都有效。这是问题... 当我正在处理和了解有关上述行为对象添加的新内容时,我有时想删除一些行为条目。

所以我这样做

activities.acts.remove(act);

我没有收到任何错误,但在下一步之后,它们似乎并没有真正被删除。

当我完成处理后,我对活动对象进行 GSON。 json 文件包含所有 act 元素,甚至包括我删除的那些元素。因此,remove element 是真的删除元素还是只是在某处设置一个标志?或者,我是不是以错误的方式处理了这个问题,我的删除并没有像我预期的那样真正起作用?

1 - How do I remove an element from my vector

按照您在此代码中所做的方式,即调用 public boolean remove(Object o) OR public E remove(int index) 方法。

activities.acts.remove(act); 应该在 activities.acts.add(act); 之后和对象转换为 JSON 之前的某处正常工作。我怀疑你所说的步骤!去掉元素后真的变成了JSON吗?

此外,尝试将删除语句的输出存储到布尔变量中。

boolean isRemoved = activities.acts.remove(act);

public boolean remove(Object o)

Removes the first occurrence of the specified element in this Vector. If the Vector does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).


  1. If I remove an element from the vector in my object and I then GSON my object to a JSON file will the element be absent from the json file? Or will the removed element still be in the json file?

如果在从对象中删除向量元素后将对象GSON到JSON文件,它肯定会不在JSON 文件。正如预期的那样简单。

此外,我建议您通过调试器查看。