If you want the elements in the collection to be repeated, it is recommended to use hashSet, as follows:
// list is an ArrayList with repeated elements. HashSet hSet = new HashSet(list); list.clear(); list.addAll(hSet);
But sometimes we want to delete an element with a duplicate attribute value (the same value), as follows:
NetWork nw1 = new NetWork();nw1.id = 1;nw1.destip = "192.168.1.3";NetWork nw2 = new NetWork();nw2.id = 2;nw2.destip = "192.168.1.5";NetWork nw3 = new NetWork();nw3.id = 3;nw3.destip = "192.168.1.3";NetWork nw4 = new NetWork();nw4.id = 4;nw4.destip = "192.168.1.4";NetWork nw5 = new NetWork();nw5.id = 5;nw5.destip = "192.168.1.3";mList.add(nw1);mList.add(nw2);mList.add(nw3);mList.add(nw4);mList.add(nw5);
Obviously, the ip values in nw1, nw3, and nw5 are the same. We only need one, so how can we loop through and delete the element values of our own using ArrayList?
for (int i = 0; i < mList.size()-1; i++) {for (int j = mList.size()-1; j > i; j--) {if (mList.get(j).destip.equals(mList.get(i).destip)) {mList.remove(j);} }}The two for loops are enough. Remember to compare them one by one from the tail. In this way, once a certain element symbol requires delete, it is necessary to ensure that the one above the tail is deleted and the loop will not be confused.
The above is the full content of the ArrayList method (recommended) that the editor brings to you. I hope it will be helpful to you and support Wulin.com more~