Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics vs Object vs Comparable

Tags:

java

types

I'm having trouble seeing the difference between when to use Generics vs Object. Right now I'm implementing quicksort and have seen examples of it done using

Generics - public static <T extends Comparable<T>> void qsort(T[] arr, int a, int b)
Objects - public static void quicksort(Object[] a, int left, int right)
Comparable - <T extends Comparable<T>> void sort(T[] a)

What really is the difference and when to use each? My goal is to make the class accessible to the largest number of data types.

like image 235
ColeKO Avatar asked Jun 10 '26 14:06

ColeKO


1 Answers

The conceptual thing to know about: Java arrays are covariant!

That means: you can write a method like

public void sort(Object[] data)

and use that with an array of Objects, but also with an Integer[], String[] whatever.

That has the advantage that you can write code that works "generically" for all kinds of different input.

But the problem with that is that it can lead to surprises at runtime, for example when your array contains Integer and String objects.

Thus the Java language folks decides to make generics, and more specifically collections of Generics invariant. Therefore you can't do

public void sort(List<Number> numbers)

and call that with some List<Integer>.

In that sense: when using arrays, then there isn't much sense in using generics. But: when using generics, you would (most of the time) prefer using collections over arrays! And then, you have to really know about the conceptual differences.

like image 78
GhostCat Avatar answered Jun 12 '26 04:06

GhostCat