How to return a generic type value in java | SoloLearn: Learn to code for FREE!


How to return a generic type value in java

This isn't working and I don't know why? Sorry if I missed something important or just very simple and obvious I came from python which has no need for generics

5/30/2020 5:30:13 PM


3 Answers

New Answer


u can pass class for generic in java but not primitive type like int. if u want to pass int/double,then u have to pass the class/wrapper for int = Integer/double = Double the problem in ur code is that Integer class dont understand what the < operator does(unlike primitive type int),so u cant use it to do comparasion(java dont have operator overload) to do comparasion, u can use compareTo() method from Comparable interface. but,, ur generic type must first get bounded with the Comparable interface(meaning that the type allowed are only for classes which implement Comparable interface,to make sure the type u are using 100% have that method) eg: static <Type extends Comparable<Type>> Type max(Type a, Type b){ if(a.compareTo(b) > 0) return a; return b; }


Lily Mea it's still not working?


12ksins you have a typo in Comparable.