Hi Experts,

I have a question. I have an object and want to insert in a text file. Before inserting, I want to check if it is duplicate. If no duplicate is found, I will insert the object. If yes, will not insert an object? Do I need a collection for this? This is for Java. Thank you!

Recommended Answers

All 3 Replies

Yes, one of the easiest ways to detect duplicates is to use a Collection that does not allow duplicates, eg HashSet. Its add method returns false if the set already contains that element.

commented: Thank you JamesCherrill.. Can we use hashset even if we have different types in the class?? +0

HashSet<Object> or. HashSet<>. or just HashSet will allow any kind of object. Primitives will be automatically wrapped with the appropriate class.

Another way is to

Convert List to Set

Set s= new HashSet(list);

Convert Set to List

List l=new ArrayList(s);

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.