Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to dynamically delete elements in ArrayList

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces you how to dynamically delete elements in ArrayList. The content is very detailed. Interested friends can refer to it for reference. I hope it can help you.

Yesterday, a project team colleague needed to delete all elements in ArrayList that were not equal to the specified value, but she worked for a long time and found that the deletion was always incomplete. I happened to have done similar functions before, so I told her that it was because the length of ArrayList became smaller after deleting elements, and the index of elements would change accordingly, but the subscripts of iterations did not change accordingly.

To summarize some of the deletion methods:

/** * Delete elements with value "c" in Arraylist */ public static void main(String[] args) { List list = new ArrayList(); //"c" is stored discontinuously in Arraylist /* list.add("c"); list.add("a"); list.add("c"); list.add("b"); list.add("c"); list.add("d"); list.add("c"); */ //"c" has continuous storage in Arraylist list.add("a"); list.add("c"); list.add("c"); list.add("b"); list.add("c"); list.add("c"); list.add("d"); list.add("c"); //Delete elements with value "c" in Arraylist //may not be able to delete all //removeListElement1(list); //can be deleted correctly //removeListElement2(list); //can be deleted correctly //removeListElement3(list); } /** * Delete elements with value "c" in list * * This way: * * When the elements with value "c" are not stored continuously in Arraylist, it is possible to delete all elements with value "c". * * However, when the element with value "c" is stored continuously in Arraylist, all the elements with value "c" are not deleted. * Because the elements are deleted, the Arraylist length is reduced and the index changes, but the index of the iteration does not decrease. */ public static void removeListElement1(List list) { for(int i=0;i

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report