从 ArrayList 中删除具有特定值的项目 [英] Remove items from ArrayList with certain value

查看:36
本文介绍了从 ArrayList 中删除具有特定值的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个对象列表并添加了人员:

I have created a list of objects and have people added to it:

ArrayList<Person> peeps = new ArrayList<Person>(); 

peeps.add(new Person("112", "John", "Smith"));
peeps.add(new Person("516", "Jane", "Smith"));
peeps.add(new Person("114", "John", "Doe"));

我想弄清楚如何通过 ID 号从列表中删除此人.因此,如果我想删除 ID 号为 114 的人,但现在没有将其删除,我该怎么办?

I am trying to figure out how to remove the person from the list by ID number. So if I wanted to remove the person with the ID number 114 but didn't now where it fell in the list, how would I?

推荐答案

如果您打算使用 ArrayList,唯一的方法是遍历整个列表,查看每个人,并查看他们的 ID 号是 114.对于较大的数据集,这不会很有效,应该避免.

If you are going to be using an ArrayList, the the only way is to go through the entire list, looking at each person, and seeing it their id number is 114. For larger datasets, this is not going to efficient and should be avoided.

如果你可以改变你的数据结构,那么某种Map 会更好(HashMap 通常是一个不错的选择).您可以将 id 号作为密钥",然后将其与每个人相关联.稍后您可以通过键查询 Map.缺点是你只能有一个值作为键,所以你不能同时说 name 和 id 数字键

If you can change your data structure, then some sort of Map would be better (HashMap is typically a good choice). You could have the id number as a "key" and then associate it with each person. Later you can query the Map by key. The con is you can only have one value as a key, so you can't have say both name and id number keys


使用 ArrayList 的一种更有效的方法是将其按 id 编号排序.然后你可以使用类似 Collections.binarySearch() 以通过 id 号快速访问元素.缺点是从排序数组中删除/插入是很昂贵的,因为必须移动元素更大的所有内容.因此,如果您打算对读取次数进行相对较少的更改,这可能是可行的


An more efficient way to do use an ArrayList would be to keep it sorted by id number. Then you can use something like Collections.binarySearch() to quickly access the elements by id number. The con is is that it is expensive to remove from/insert into a sorted array, as everything greater the element has to be moved. So if you are going to be doing relatively few changes compared to the number of reads, this might be viable

这篇关于从 ArrayList 中删除具有特定值的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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