Collections.disjoint(Collection, Collection) in Java

Collections.disjoint(Collection, Collection): This method is available in java.util.Collections class of Java.

Syntax:

boolean java.util.Collections.disjoint(Collection<?> c1, Collection<?> c2)

This method takes two arguments. This method returns true if the two specified collections have no elements in common.

Parameters: Two parameters are required for this method.

c1: a collection.

c2: a collection

Returns: true if the two specified collections have no elements in common.

Throws:

1. NullPointerException - if either collection is null or if one collection contains a null element and null is not an eligible element for the other collection.

2. ClassCastException - if one collection contains an element that is of a type that is eligible for the other collection.

Approach 1: When no exception

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Collectionsdisjoint {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);

        arrlist.add(13);
        arrlist.add(4);

        List<Integer> arrlist2 = new ArrayList<Integer>();
        arrlist2.add(1000);
        arrlist2.add(10000);
        arrlist2.add(100);
        System.out.println(Collections.disjoint(arrlist,
arrlist2));

    }
}

Output:

true


Approach 2: NullPointerException 

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Collectionsdisjoint {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);

        arrlist.add(13);
        arrlist.add(4);

        List<Integer> arrlist2 = null;
        System.out.println(Collections.disjoint(arrlist,
arrlist2));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.size()" because "c2" is null at java.base/java.util.Collections.disjoint(Collections.java:5539)


No comments:

Post a Comment