Home  >  Core Java

Example of Collections.disjoint in Java

By Arvind Rai, May 26, 2013
Java Collections.disjoint checks if two collections are mutually exclusive. The class whose objects are being kept in collection must be able to check two objects equality. The class should override hashCode() and equals(). Find the example.
CollectionsDisjointDemo.java
package com.concretepage.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDisjointDemo {
    public static void main(String[] args) {
        Person a1 = new Person("AAAA");
        Person a2 = new Person("BBBB");
        Person a3 = new Person("CCCC");
        Person a4 = new Person("DDDD");
        Person a5 = new Person("EEEE");
        Person a6 = new Person("FFFF");
        List<Person> list1 = new ArrayList<Person>();
        list1.add(a1);
        list1.add(a2);
        list1.add(a3);
        List<Person> list2 = new ArrayList<Person>();
        list2.add(a4);
        list2.add(a5);
        list2.add(a6);
        System.out.println(Collections.disjoint(list1, list2));
        //Now add a common value
        Person a7 = new Person("BBBB");
        list2.add(a7);
        System.out.println(Collections.disjoint(list1, list2));        
   }
}
class Person {
    private String name;
    public Person(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        return name.equals(((Person)o).name);
    }
    @Override
    public int hashCode() {
        int hash = 13;
        hash = (31 * hash) + (null == name ? 0 : name.hashCode());
        return hash;
    }
    public String getName() {
	return name;
    }
}
Output
true
false
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us