Menu
Topics Index
...
`

Collections1658


If you need explanation Read this topic

If you need Answer Take test on this topic

Collections1658
What will be the output of the following program?
import java.util.*;
class AlgorithmTest {
    public static int findFirst(List<T> list, int begin, int end, UnaryPredicate<T> p) {
        for (; begin < end; ++begin)
            if (p.test(list.get(begin)))
                return begin;
        return -1;
    }
    public static int highestCommomFactor(int x, int y) {
        for (int r; (r = x % y) != 0; x = y, y = r) {}
        return y;
    }
}
interface UnaryPredicate<T> {
    public boolean test(T t);
}
class RelativelyPrimePredicate implements UnaryPredicate<Integer> {
    public RelativelyPrimePredicate(Collection<Integer> c) {
        this.c = c;
    }
    public boolean test(Integer x) {
        for (Integer i : c)
            if (AlgorithmTest.highestCommomFactor(x, i) != 1)
                return false;
        return c.size() > 0;
    }
    private final Collection<Integer> c;
}
public class Algorithm {
    public static void main(String[] args) {
        List<Integer> li = Arrays.asList(3, 4, 6, 8, 11, 15, 28, 32);
        Collection<Integer> c = Arrays.asList(7, 18, 19, 25);
        UnaryPredicate<Integer> p = new RelativelyPrimePredicate(c);
        System.out.print("Output is: " + li.get(AlgorithmTest.findFirst(li, 0, li.size(), p)));
    }
}

A. Output is: 11
B. Output is: -1
C. Compilation Error
D. Runtime Error
Topic: java.util.Arrays - Class Arrays In Collection Framework

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans is B....only hcf of two prime no's is 1...bt in collections c 18,25 are not prime...so irrespective of ele's in list the return c.size()>0 is never executed..so it returns false so -1 is returned in findFirst...

Posted by Santosh Munugota    2013-07-30 12:47:02


a is ans bcz p.test(list.get(begin))is  true till begin=4 so loop iterates till 4 and returns4 to the list.get so it wil print 11

Posted by Manasa Sudini    2013-07-30 12:49:00


c

Posted by Kavya Kathi    2013-07-30 13:19:59


d

Posted by Aruna Dantu    2013-07-30 13:39:34


D

Posted by Ys Abhinav    2013-07-30 15:34:35


The answer is C , because, when we are using the generic methods we should mention the genetic type i.e.,<T> before the method return type which is missing for the method 'findFirst(..)'. so, it causes the compilation error. The correct declaration is public static <T> int findFirst(...)

Posted by Merit Campus    2013-07-31 03:55:37


Since no one has given correct answer and explanation there is no winner for this.

Posted by Merit Campus    2013-07-31 03:56:32


© meritcampus 2019

All Rights Reserved.

Open In App