Posts

Showing posts with the label java

Difference between Callable and Runnable and Future?

In Java, Callable, Runnable, and Future are three related interfaces that are used to perform concurrent programming and retrieve results. Here are the key differences between them: Callable Interface The Callable interface is a functional interface that represents a task that returns a result and may throw an exception.  It has a single method: V call() throws Exception; Here, V is the type of result returned by the task. The call() method must be implemented by the class that implements the Callable interface. Runnable Interface The Runnable interface is a functional interface that represents a task that does not return a result and may throw an exception. It has a single method: void run(); Here, the run() method must be implemented by the class that implements the Runnable interface. Future Interface The Future interface represents the result of an asynchronous computation. It provides methods to check whether the computation is complete, retrieve the result of the computation,...

What is the difference between Comparable and Comparator Interface?

In Java, both the Comparable and Comparator interfaces are used for comparing objects, but they have different ways of achieving this. Comparable : The Comparable interface is used to define a natural ordering of objects. When a class implements Comparable, it defines a default ordering of objects of that class. The Comparable interface contains a single method, compareTo(), which takes an object of the same type as the implementing class and returns an integer value indicating whether the object is greater than, equal to, or less than the object being compared to. The compareTo() method is used by collections, such as TreeSet and TreeMap, to sort elements. Comparator : The Comparator interface is used to define a custom ordering of objects that do not implement Comparable or when a different ordering is required. The Comparator interface contains two methods, compare() and equals(). The compare() method takes two objects of the type being compared and returns an integer value indicat...