从ArrayList中删除具有特定值的项目 [英] Remove items from ArrayList with certain value
问题描述
我创建了一个对象列表,并添加了人员:
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.
如果您可以更改数据结构,则可以使用地图会更好( HashMap 通常是一个不错的选择).您可以将ID号作为键",然后将其与每个人相关联.稍后,您可以按键查询地图.缺点是您只能使用一个值作为键,因此您不能同时说出姓名和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屋!