Removing duplicates from an Array of Strings, without explicit comparison in Java

柔情痞子 提交于 2019-12-14 04:14:57

问题


What would be the best means of going about this without explicit comparison?


回答1:


If List Of Object contains Strings , You need to Add them to Set.

If the list contains Custom object , override equals meth in the custom class and those object to Set




回答2:


- Use Collection named Set, which maintains Uniqueness.

- Use asList() method of Array to convert it into List, and then use addAll() method to add the List to the Set.

- Adding List to the Set will remove the duplicates.

Eg:

String[] arr = {"Vivek","John","Rick"};

ArrayList<String> arList = new ArrayList<String>(Arrays.asList(arr));

TreeSet<String> arSet = new TreeSet<String>();

arSet.addAll(arList);       // duplicates removed


来源:https://stackoverflow.com/questions/13812807/removing-duplicates-from-an-array-of-strings-without-explicit-comparison-in-jav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!