I want to know how to check gracefully whether 2 sets are distinct or has at least 1 element in common. I don't want to find the common elements. Just knowing whether there is intersection or not is sufficient. May be I can do this using retainsAll but it changes the content of one set. And it seems like a roundabout way of doing a simple thing.

Set<Integer> s1 = new HashSet<Integer>();
		Set<Integer> s2 = new HashSet<Integer>();
		
		s1.add(1);
		s1.add(2);
		s2.add(2);
		
		System.out.println(s1.retainAll(s2));
		System.out.println(s1);

In the code above whether I add element 2 or 3 to s2, retainAll always shows to be true. So I can't test it credibly. I wonder what is the purpose of the return value of retainAll. Because whether there is any element in common or not it is showing true all the time. I am kind of pissed of with it.

> I want to know how to check gracefully whether 2 sets are distinct

Try using the Collections.disjoint() method for this.

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.