Java - derived generics class for math functions - java

This was a hard problem to try and search for as I've seen no other specific issues like this, so I apologize if there turns out to be a duplicate thread I haven't found. This is a programming problem that is not related to homework in a class, that I am having issues implementing exactly according to spec.
If I want to create a
Function<T>
generic abstract class, whose only abstract method is
Apply<T>(T input1, input2)
and then extend into other derived function classes like an AddTwoNumbers class, to which Apply would return the sum of those input1 and input2 of type T (in practice this should be Integer or Double), how can I implement this?
I run into a problem when I first have
public abstract class Function<T1 extends Number> {
public abstract T1 apply(T1 input1, T1 input2);
}
public class AddTwoNumbers<T1 extends Number> extends Function<T1> {
public T1 apply(T1 input1, T1 input2) {
return input1.intValue() + input2.intValue(); //Error, needs to return type T1, not int or even Integer()
}
}
It is required that Function be generic that allows types, but inpractice it can be expected that AddTwoNumbers will be using Integers exclusively for the sake of this problem. Is there a way I can write the apply() method in AddTwoNumbers, such that
AddTwoNumbers implements the abstract methods inherited from Function exactly
Somehow add the two T1 values and return a T1 value properly?
The fact that I can't safely cast a T1 to an Integer, and also retain the overriding of Apply is the troublesome part.
This is generalization of the issue I was looking into.

public class AddTwoIntegers extends Function< Integer > {
...
}

What you're asking for unfortunately isn't possible within the Java specification. There is no abstraction layer which accounts for both primitive ints and primitive doubles, or in fact any combination of primitives, so you are forced to create two classes for this.
There are ways of doing this, however, which are much better than writing an AddTwoIntegers.java file AND an AddTwoDoubles.java file.
Option 1: Create an AdditionFunctions class, and give it two static members: INTS and DOUBLES. You can do this using anonymous classes easily.
Option 2: Use a template, if you can incorporate the generation step into your build process. Trove does this to great effect

Related

Why can the Monad interface not be declared in Java?

Before you start reading: This question is not about understanding monads, but it is about identifying the limitations of the Java type system which prevents the declaration of a Monad interface.
In my effort to understand monads I read this SO-answer by Eric Lippert on a question which asks about a simple explanation of monads. There, he also lists the operations which can be executed on a monad:
That there is a way to take a value of an unamplified type and turn it into a value of the amplified type.
That there is a way to transform operations on the unamplified type into operations on the amplified type that obeys the rules of functional composition mentioned before
That there is usually a way to get the unamplified type back out of the amplified type. (This last point isn't strictly necessary for a monad but it is frequently the case that such an operation exists.)
After reading more about monads, I identified the first operation as the return function and the second operation as the bind function. I was not able to find a commonly used name for the third operation, so I will just call it the unbox function.
To better understand monads, I went ahead and tried to declare a generic Monad interface in Java. For this, I first looked at the signatures of the three functions above. For the Monad M, it looks like this:
return :: T1 -> M<T1>
bind :: M<T1> -> (T1 -> M<T2>) -> M<T2>
unbox :: M<T1> -> T1
The return function is not executed on an instance of M, so it does not belong into the Monad interface. Instead, it will be implemented as a constructor or factory method.
Also for now, I omit the unbox function from the interface declaration, since it is not required. There will be different implementations of this function for the different implementations of the interface.
Thus, the Monad interface only contains the bind function.
Let's try to declare the interface:
public interface Monad {
Monad bind();
}
There are two flaws:
The bind function should return the concrete implementation, however it does only return the interface type. This is a problem, since we have the unbox operations declared on the concrete subtypes. I will refer to this as problem 1.
The bind function should retrieve a function as a parameter. We will address this later.
Using the concrete type in the interface declaration
This addresses problem 1: If my understanding of monads is correct, then the bind function always returns a new monad of the same concrete type as the monad where it was called on. So, if I have an implementation of the Monad interface called M, then M.bind will return another M but not a Monad. I can implement this using generics:
public interface Monad<M extends Monad<M>> {
M bind();
}
public class MonadImpl<M extends MonadImpl<M>> implements Monad<M> {
#Override
public M bind() { /* do stuff and return an instance of M */ }
}
At first, this seems to work, however there are at least two flaws with this:
This breaks down as soon as an implementing class does not provide itself but another implementation of the Monad interface as the type parameter M, because then the bind method will return the wrong type. For example the
public class FaultyMonad<M extends MonadImpl<M>> implements Monad<M> { ... }
will return an instance of MonadImpl where it should return an instance of FaultyMonad. However, we can specify this restriction in the documentation and consider such an implementation as a programmer error.
The second flaw is more difficult to resolve. I will call it problem 2: When I try to instantiate the class MonadImpl I need to provide the type of M. Lets try this:
new MonadImpl<MonadImpl<MonadImpl<MonadImpl<MonadImpl< ... >>>>>()
To get a valid type declaration, this has to go on infinitely. Here is another attempt:
public static <M extends MonadImpl<M>> MonadImpl<M> create() {
return new MonadImpl<M>();
}
While this seems to work, we just defered the problem to the called. Here is the only usage of that function that works for me:
public void createAndUseMonad() {
MonadImpl<?> monad = create();
// use monad
}
which essentially boils down to
MonadImpl<?> monad = new MonadImpl<>();
but this is clearly not what we want.
Using a type in its own declaration with shifted type parameters
Now, let's add the function parameter to the bind function: As described above, the signature of the bind function looks like this: T1 -> M<T2>. In Java, this is the type Function<T1, M<T2>>. Here is the first attempt to declare the interface with the parameter:
public interface Monad<T1, M extends Monad<?, ?>> {
M bind(Function<T1, M> function);
}
We have to add the type T1 as generic type parameter to the interface declaration, so we can use it in the function signature. The first ? is the T1 of the returned monad of type M. To replace it with T2, we have to add T2 itself as a generic type parameter:
public interface Monad<T1, M extends Monad<T2, ?, ?>,
T2> {
M bind(Function<T1, M> function);
}
Now, we get another problem. We added a third type parameter to the Monad interface, so we had to add a new ? to the usage of it. We will ignore the new ? for now to investigate the now first ?. It is the M of the returned monad of type M. Let's try to remove this ? by renaming M to M1 and by introducing another M2:
public interface Monad<T1, M1 extends Monad<T2, M2, ?, ?>,
T2, M2 extends Monad< ?, ?, ?, ?>> {
M1 bind(Function<T1, M1> function);
}
Introducing another T3 results in:
public interface Monad<T1, M1 extends Monad<T2, M2, T3, ?, ?>,
T2, M2 extends Monad<T3, ?, ?, ?, ?>,
T3> {
M1 bind(Function<T1, M1> function);
}
and introducing another M3 results in:
public interface Monad<T1, M1 extends Monad<T2, M2, T3, M3, ?, ?>,
T2, M2 extends Monad<T3, M3, ?, ?, ?, ?>,
T3, M3 extends Monad< ?, ?, ?, ?, ?, ?>> {
M1 bind(Function<T1, M1> function);
}
We see that this will go on forever if we try to resolve all ?. This is problem 3.
Summing it all up
We identified three problems:
Using the concrete type in the declaration of the abstract type.
Instantiating a type which receives itself as generic type parameter.
Declaring a type which uses itself in its declaration with shifted type parameters.
The question is: What is the feature that is missing in the Java type system? Since there are languages which work with monads, these languages have to somehow declare the Monad type. How do these other languages declare the Monad type? I was not able to find information about this. I only find information about the declaration of concrete monads, like the Maybe monad.
Did I miss anything? Can I properly solve one of these problems with the Java type system? If I cannot solve problem 2 with the Java type system, is there a reason why Java does not warn me about the not instantiable type declaration?
As already stated, this question is not about understanding monads. If my understanding of monads is wrong, you might give a hint about it, but don't attempt to give an explanation. If my understanding of monads is wrong the described problems remain.
This question is also not about whether it is possible to declare the Monad interface in Java. This question already received an answer by Eric Lippert in his SO-answer linked above: It is not. This question is about what exactly is the limitation that prevents me from doing this. Eric Lippert refers to this as higher types, but I can't get my head around them.
Most OOP languages do not have a rich enough type system to represent the monad pattern itself directly; you need a type system that supports types that are higher types than generic types. So I wouldn't try to do that. Rather, I would implement generic types that represent each monad, and implement methods that represent the three operations you need: turning a value into an amplified value, turning an amplified value into a value, and transforming a function on unamplified values into a function on amplified values.
What is the feature that is missing in the Java type system? How do these other languages declare the Monad type?
Good question!
Eric Lippert refers to this as higher types, but I can't get my head around them.
You are not alone. But they are actually not as crazy as they sound.
Let's answer both of your questions by looking at how Haskell declares the monad "type" -- you'll see why the quotes in a minute. I have simplified it somewhat; the standard monad pattern also has a couple other operations in Haskell:
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
Boy, that looks both incredibly simple and completely opaque at the same time, doesn't it?
Here, let me simplify that a bit more. Haskell lets you declare your own infix operator for bind, but we'll just call it bind:
class Monad m where
bind :: m a -> (a -> m b) -> m b
return :: a -> m a
All right, now at least we can see that there are the two monad operations in there. What does the rest of this mean?
The first thing to get your head around, as you note, is "higher kinded types". (As Brian points out, I somewhat simplified this jargon in my original answer. Also quite amusing that your question attracted the attention of Brian!)
In Java, a "class" is a kind of "type", and a class may be generic. So in Java we've got int and IFrob and List<IBar> and they're all types.
From this point on throw away any intuition you have about Giraffe being a class that is a subclass of Animal, and so on; we won't need that. Think about a world with no inheritance; it will not come into this discussion again.
What are classes in Java? Well, the easiest way to think of a class is that it is a name for a set of values that have something in common, such that any one of those values can be used when an instance of the class is required. You have a class Point, lets say, and if you have a variable of type Point, you can assign any instance of Point to it. The Point class is in some sense just a way to describe the set of all Point instances. Classes are a thing that is higher than instances.
In Haskell there are also generic and non-generic types. A class in Haskell is not a kind of type. In Java, a class describes a set of values; any time you need an instance of the class, you can use a value of that type. In Haskell a class describes a set of types. That is the key feature that the Java type system is missing. In Haskell a class is higher than a type, which is higher than an instance. Java only has two levels of hierarchy; Haskell has three. In Haskell you can express the idea "any time I need a type that has certain operations, I can use a member of this class".
(ASIDE: I want to point out here that I am making a bit of an oversimplification . Consider in Java for example List<int> and List<String>. These are two "types", but Java considers them to be one "class", so in a sense Java also has classes which are "higher" than types. But then again, you could say the same in Haskell, that list x and list y are types, and that list is a thing that is higher than a type; it's a thing that can produce a type. So it would in fact be more accurate to say that Java has three levels, and Haskell has four. The point remains though: Haskell has a concept of describing the operations available on a type that is simply more powerful than Java has. We'll look at this in more detail below.)
So how is this different than interfaces? This sounds like interfaces in Java -- you need a type that has certain operations, you define an interface that describes those operations. We'll see what is missing from Java interfaces.
Now we can start making sense of this Haskell:
class Monad m where
So, what is Monad? It's a class. What is a class? It's a set of types that have something in common, such that whenever you need a type that has certain operations, you can use a Monad type.
Suppose we have a type that is a member of this class; call it m. What are the operations that must be on this type in order for that type to be a member of the class Monad?
bind :: m a -> (a -> m b) -> m b
return :: a -> m a
The name of the operation comes to the left of the ::, and the signature comes to the right. So to be a Monad, a type m must have two operations: bind and return. What are the signatures of those operations? Let's look at return first.
a -> m a
m a is Haskell for what in Java would be M<A>. That is, this means m is a generic type, a is a type, m a is m parametrized with a.
x -> y in Haskell is the syntax for "a function which takes type x and returns type y". It's Function<X, Y>.
Put it together, and we have return is a function that takes an argument of type a and returns a value of type m a. Or in Java
static <A> M<A> Return(A a);
bind is a little bit harder. I think the OP well understands this signature, but for readers who are unfamiliar with the terse Haskell syntax, let me expand on this a bit.
In Haskell, functions only take one argument. If you want a function of two arguments, you make a function that takes one argument and returns another function of one argument. So if you have
a -> b -> c
Then what have you got? A function that takes an a and returns a b -> c. So suppose you wanted to make a function that took two numbers and returned their sum. You would make a function that takes the first number, and returns a function that takes a second number and adds it to the first number.
In Java you'd say
static <A, B, C> Function<B, C> F(A a)
So if you wanted a C and you had and A and a B, you could say
F(a)(b)
Make sense?
All right, so
bind :: m a -> (a -> m b) -> m b
is effectively a function that takes two things: an m a, and a a -> m b and it returns an m b. Or, in Java, it is directly:
static <A, B> Function<Function<A, M<B>>, M<B>> Bind(M<A>)
Or, more idiomatically in Java:
static <A, B> M<B> Bind(M<A>, Function<A, M<B>>)
So now you see why Java cannot represent the monad type directly. It does not have the ability to say "I have a class of types that have this pattern in common".
Now, you can make all the monadic types you want in Java. The thing you can't do is make an interface that represents the idea "this type is a monad type". What you would need to do is something like:
typeinterface Monad<M>
{
static <A> M<A> Return(A a);
static <A, B> M<B> Bind(M<A> m, Function<A, M<B>> f);
}
See how the type interface talks about the generic type itself? A monadic type is any type M that is generic with one type parameter and has these two static methods. But you can't do that in the Java or C# type systems. Bind of course could be an instance method that takes an M<A> as this. But there is no way to make Return anything but static. Java gives you no ability to (1) parameterize an interface by an unconstructed generic type, and (2) no ability to specify that static members are part of the interface contract.
Since there are languages which work with monads, these languages have to somehow declare the Monad type.
Well you'd think so but actually not. First off, of course any language with a sufficient type system can define monadic types; you can define all the monadic types you want in C# or Java, you just can't say what they all have in common in the type system. You can't make a generic class that can only be parameterized by monadic types, for instance.
Second, you can embed the monad pattern in the language in other ways. C# has no way to say "this type matches the monad pattern", but C# has query comprehensions (LINQ) built into the language. Query comprehensions work on any monadic type! It's just that the bind operation has to be called SelectMany, which is a little weird. But if you look at the signature of SelectMany, you'll see that it is just bind:
static IEnumerable<R> SelectMany<S, R>(
IEnumerable<S> source,
Func<S, IEnumerable<R>> selector)
That's the implementation of SelectMany for the sequence monad, IEnumerable<T>, but in C# if you write
from x in a from y in b select z
then a's type can be of any monadic type, not just IEnumerable<T>. What is required is that a is M<A>, that b is M<B>, and that there is a suitable SelectMany that follows the monad pattern. So that's another way of embedding a "monad recognizer" in the language, without representing it directly in the type system.
(The previous paragraph is actually a lie of oversimplification; the binding pattern used by this query is slightly different than the standard monadic bind for performance reasons. Conceptually this recognizes the monad pattern; in actuality the details differ slightly. Read about them here http://ericlippert.com/2013/04/02/monads-part-twelve/ if you're interested.)
A few more small points:
I was not able to find a commonly used name for the third operation, so I will just call it the unbox function.
Good choice; it is usually called the "extract" operation. A monad need not have an extract operation exposed, but of course somehow bind needs to be able to get the A out of the M<A> in order to call the Function<A, M<B>> on it, so logically some sort of extraction operation usually exists.
A comonad -- a backwards monad, in a sense -- requires an extract operation to be exposed; extract is essentially return backwards. A comonad as well requires an extend operation that is sort of bind turned backwards. It has the signature static M<B> Extend(M<A> m, Func<M<A>, B> f)
If you look at what the AspectJ project is doing, it is similar to applying monads to Java. The way they do it is to post-process the byte code of the classes to add the additional functionality-- and the reason they have to do that is because there is no way within the language without the AspectJ extensions to do what they need to do; the language is not expressive enough.
A concrete example: say you start with class A. You have a monad M such that M(A) is a class that works just like A, but all method entrances and exits get traced to log4j. AspectJ can do this, but there is no facility within the Java language itself that would let you.
This paper describes how Aspect-Oriented Programming as in AspectJ might be formalized as monads
In particular, there is no way within the Java language to specify a type programmatically (short of byte-code manipulation a la AspectJ). All types are pre-defined when the program starts.
Good question indeed! :-)
As #EricLippert pointed out, the type of polymorphism that is known as "type classes" in Haskell is beyond the grasp of Java's type system. However, at least since the introduction of the Frege programming language it has been shown that a Haskell-like type system can indeed be implemented on top of the JVM.
If you want to use higher-kinded types in the Java language itself you have to resort to libraries like highJ or Cyclops. Both libraries do provide a monad type class in the Haskell sense (see here and here, respectively, for the sources of the monad type class). In both cases, be prepared for some major syntactic inconveniences; this code will not look pretty at all and carries a lot of overhead to shoehorn this functionality into Java's type system. Both libraries use a "type witness" to capture the core type separately from the data type, as John McClean explains in his excellent introduction. However, in neither implementation you will find anything as simple and straightforward as Maybe extends Monad or List extends Monad.
The secondary problem of specifying constructors or static methods with Java interfaces can be easily overcome by introducing a factory (or "companion") interface that declares the static method as a non-static one. Personally, I always try to avoid anything static and use injected singletons instead.
Long story short, yes, it is possible to represent HKTs in Java but at this point it is very inconvenient and not very user friendly.
Yes, we cannot override static method in class, and we cannot write constructor in interface.
use abstract class to simulate Monad type class in Haskell
import java.util.function.Function;
public abstract class Monad<T> {
public static <T> Monad<T> Unit(T a){
throw new UnsupportedOperationException("Call Unit in abstract class: Monad");
}
public <R> Monad<R> OUnit(R a){
throw new UnsupportedOperationException("Call OUnit in abstract class: Monad");
}
public <B> Monad<B> bind(Function<T, Monad<B>> func){
throw new UnsupportedOperationException("Call bind in abstract class: Monad");
}
public <B> Monad<B> combine(Monad<B> b){
return this.bind(unused -> b);
}
}
public class Maybe<T> extends Monad<T> {
public boolean has;
public T val;
public Maybe(T value) {
this.has = true;
this.val = value;
}
public Maybe(){
has = false;
}
public static <T> Maybe<T> Unit(T a) {
return new Maybe<T>(a);
}
public static <T> Maybe<T> Unit() {
return new Maybe<T>();
}
#Override
public <R> Maybe<R> OUnit(R a) {
return new Maybe<R>(a);
}
public <T> Maybe<T> OUnit() {
return new Maybe<T>();
}
#Override
public <B> Monad<B> bind(Function<T, Monad<B>> func){
if (this.has){
return func.apply(this.val);
}
return new Maybe<B>();
}
#Override
public String toString(){
if (this.has){
return "Maybe " + val.toString();
}
return "Nothing";
}
}
public class Main {
/*
example :: (Monad m, Show (m n), Num n) => m n -> m n -> IO ()
example a b = do
print $ a >> b
print $ b >> a
print $ a >>= (\x -> return $ x+x)
print $ b >>= (\x -> return $ x+x)
main = do
example (Just 10) (Just 5)
example (Right 10) (Left 5)
*/
public static void example(Monad<Integer> a, Monad<Integer> b){
System.out.println(a.bind(x -> b));
System.out.println(b.bind(x -> b));
System.out.println(a.bind(x -> a.OUnit(x*2)));
System.out.println(b.bind(x -> b.OUnit(x*2)));
System.out.println(a.combine(a));
System.out.println(a.combine(b));
System.out.println(b.combine(a));
System.out.println(b.combine(b));
}
// Monad can also used in any Objects
public static void example2(Monad<Object> a, Monad<Object> b){
System.out.println(a.bind(x -> b));
System.out.println(b.bind(x -> b));
System.out.println(a.combine(a));
System.out.println(a.combine(b));
System.out.println(b.combine(a));
System.out.println(b.combine(b));
}
public static void main(String[] args){
System.out.println("Example 1:");
example(Maybe.<Integer>Unit(10), Maybe.<Integer>Unit());
System.out.println("\n\nExample 2:");
example(Maybe.<Integer>Unit(1), Maybe.<Integer>Unit(3));
System.out.println("\n\nExample 3:");
example2(Maybe.<Object>Unit(10), Maybe.<Object>Unit());
}
}
use interface to simulate Monad type class in Haskell
import java.util.function.Function;
public interface Monad<T> {
public static <T> Monad<T> Unit(T a){
throw new UnsupportedOperationException("call Unit in Monad interface");
}
public <R> Monad<R> OUnit(R a);
public <B> Monad<B> bind(Function<T, Monad<B>> func);
default public <B> Monad<B> combine(Monad<B> b){
return bind(x-> b);
};
}
// in class Maybe, replace extends with implements
// in class Main, unchanged
and the output is the same

How to allow a generic class method to be executed only by certain types of parameters?

I am trying to add a method to an existing class BinaryTree<T> to simple add the values of all the elements in the tree. The problem is that being the class a generic one, not all the types that can be send at the time of creating a tree can be added. I mean, for example It wouldn't make any sense to try to add the values of a class people.
So my question is, how do I make a method public T addAllElements() that only allows T to be an specific kind of type, in this case, only the types that is possible to add it's value, like Integer, Float, Long, etc? I guess there have to be some kind of numerical interface or maybe some kind of declaration provided by the language to do something like that.
By the way, it seems to be a solution without having to create a child class, in case that it could help in anything, because I was asked to solve a similar problem and the instructions says that the method have to be in the same class.
Trying to be more clear, I'll ask another question , because I think that both of them have the same answer.
I found that the method sort() in java.util.Arrays class can be used by a class if the class implements the interface Comparable<T>. So if I hava a class, lets say
public class People {
implements Comparable<People>
private String name;
public int compareTo(People o) {
...
}
...
}
This class can be sorted with the sort() method from the Arrays class, but if the class dind't implement the Comparable<T> interface it couldn't. So what is making this restriction in the Arrays class definition? Is it what I need to solve the first problem I asked?
So my question is, how do I make a method publicTaddAllElements() that only allows T to be an specific kind of type, in this case, only the types that is possible to add it's value, like int, float, long, etc? I guess there have to be some kind of numerical interface or maybe some kind of declaration provided by the language to do something like that.
You're looking for Number.
So your declaration would look something like this, if the class is generic:
public BinaryTree<T extends Number> {
// ...
}
or if you want to make just the method generic:
public <T extends Number> T addAllElements() {
// ...
}
That said, for better or for worse Number does not define arithmetic operations in terms of methods. To my knowledge there is no such built-in type which does.
Do note that the types you listed are all primitives, which mean they're not compatible with generics at all. Subtypes of Number (and types that can be used with generics) will all be wrapper types: Integer, Float, Long, etc.
Your examples are related, but they're not the same.
To address the latter concern first, the reason that Arrays.sort with a specific signature requires that things be Comparable is because it needs to sort them based on that natural ordering. There is another signature that you could provide to the method which allows you to pass a custom Comparator to it, to sort on whatever other property of the class you liked.
To your main concern, you need to have an upper-bound generic, specifically one of type T extends Number. The reason for this is that Number is the parent class to all of the numeric wrapper classes, as well as BigDecimal and BigInteger.
There's two things you'd want to be sure of before you did this:
Your generic type was bound at the class level. Since we're dealing with a tree, it makes no sense to have non-homogeneous data throughout.
You did a math operation according to a specific data type (int, long, or double).
You would then declare your method(s) as such:
public int addAsInteger() {}
public double addAsDouble() {}
public long addAsLong() {}
You'd make use of Number's methods: intValue, longValue and doubleValue for your respective methods.
You wouldn't be able to simply return T since you can't guarantee what kind of Number you're getting back, or what T is specifically bound to (it can't be Number since it's an abstract class, so it is a non-inclusive upper bound).

How to make polymorphism in java when using basic types like int?

I am a new hand of Java programming, so if there is anything misused, remind and excuse me.
I can make polymorphism when dealing with class types, say:
class A{}
class B{}
void method(Object obj){
if (obj instanceof A) {}
else if (obj instance of B){}
else {}
}
I can pass different classes to call different part of method(), but when dealing with basic types like int, it is not inherited from Object.
I know actually this is not strict polymorphism, because there is not override. Maybe, generic programming is a more proper name, but I don't know whether this is right.
If you are trying to do what you are talking about (which isn't quite polymorphism) with basic data types, you could try to use Integers, instead of ints. ints are raw data, which are stored by their value. Integer is a class, and has all the functionality of one (plus auto-boxing/unboxing, but don't worry about that).
Because Integer is a class, you can extend it and do what your are talking about with the instanceof stuff.
There are also (Long)s, (Double)s, (Boolean)s, et cetera
You can define few methods with the same name and different argument types like that:
void method(int a) {}
void method(long a) {}
void method(double a) {}
As #ByteCommander mentioned it's called overloading
I think it's what you meant. In this case when you call:
int a = 1; method(a);
you will execute first method defined. And so on...

Java Generics, support "Specialization"? Conceptual similarities to C++ Templates?

I know quite a bit how to use C++-Templates -- not an expert, mind you. With Java Generics (and Scala, for that matter), I have my diffuculties. Maybe, because I try to translate my C++ knowledge to the Java world. I read elsewhere, "they are nothing alike: Java Generics are only syntactic sugar saving casts, C++ Templates are only a glorified Preprocessor" :-)
I am quite sure, both is a bit simplified a view. So, to understand the big and the subtle differences, I try to start with Specialization:
In C++ I can design a Template (class of function) that acts on any type T that supports my required operations:
template<typename T>
T plus(T a, T b) { return a.add(b); }
This now potentially adds the plus() operation to any type that can add().[note1][1]
Thus, if T supports the add(T) my template woll work. If it doesn't,
The compiler will not complain as long as I do not use plus(). In Python
we call this "duck typing": *If it acts like a duck, quacks like a duck,
it is a duck.* (Of course, with using type_traits this is modified a bit,
but as long as we have no concepts, this is how C++ Templates work, right?)
I guess, thats how Generics in Java work as well, isn't it? The generic type I device is used as a "template" how to operate on any anything I try to put in there, right? As far as I understand I can (or must?) put some constraints on the type arguments: If I want to use add in my template, I have to declare the type argument to implement Addable. Correct? So, no "duck typing" (for better or worse).
Now, in C++ I can choose to specialize on a type that has no add():
template<>
T plus<MyX>(MyX a, MyX b) { return a + b; }
And even if all other types still can use the "default" implementation, now I added a special one for MyX -- with no runtime overhead.
Is there any Java Generics mechanism that has the same purpose? Of course, in programming everything is doable, but I mean conceptually, without any tricks and magic?
No, generics in Java don't work this way.
With generics you can't do anything which would not be possible without Generics - you just avoid to have to write lots of casts, and the compiler ensures that everything is typesafe (as long as you don't get some warnings or suppress those).
So, for each type variable you can only call the methods defined in its bounds (no duck typing).
Also, there is no code generation (apart from some adapter methods to delegate to methods with other parameter types for the purpose of implementing generic types). Assume you had something like this
/**
* interface for objects who allow adding some other objects
*/
interface Addable<T> {
/** returns the sum of this object and another object. */
T plus(T summand);
}
Then we could create our sum method with two arguments:
public static <T extends Addable<T>> T sum(T first, T second) {
return first.plus(second);
}
The static method is compiled to the same bytecode like this (with additional type information in annotations):
public static Addable sum(Addable first, Addable second) {
return first.plus(second);
}
This is called type erasure.
Now this method can be called for every pair of two elements of an addable type, like this one:
public class Integer implements Addable<Integer> {
public Integer plus(Integer that) {
return new Integer(this.value + that.value);
}
// private implementation details omitted
}
What here happens is that the compiler creates an additional synthetic method like this:
public Object plus(Object that) {
return this.plus((Integer)that);
}
This method will only be called by generic code with the right types, this guarantees the compiler, assuming you are not doing some unsafe casts somewhere - then the (Integer) cast here will catch the mistake (and throw a ClassCastException).
The sum method now always calls the plus method of the first object, there is no way around this. There is not code generated for every type argument possible (this is the key difference between Java generics and C++ templates), so we can't simply replace one of the generated method with a specialized one.
Of course, you can create a second sum method like irreputable proposed (with overloading), but this will only be selected if you use the MyX type directly in source code, not when you are calling the sum method from some other generic code which happens to be parametrized with MyX, like this:
public static <T extends Addable<T>> product (int times, T factor) {
T result = factor;
while(n > 1) {
result = sum(result, factor);
}
return result;
}
Now product(5, new MyX(...)) will call our sum(T,T) method (which in turn calls the plus method), not any overloaded sum(MyX, MyX) method.
(JDK 7 adds a new dynamic method dispatch mode which allows specialization by every argument on run time, but this is not used by the Java language, only intended to be used by other JVM-based languages.)
no - but your particular problem is more of an overloading issue.
There's no problem to define 2 plus methods like these
<T extends Addable>
T plus(T a, T b) { .. }
MyX plus(MyX a, MyX b) { .. }
This works even if MyX is an Addable; javac knows that the 2nd plus is more specific than the 1st plus, so when you call plus with two MyX args, the 2nd plus is chosen. In a sense Java does allow "specialized" version of methods:
f(T1, T2, .. Tn)
f(S1, S2, .. Sn)
works great if each Si is a subtype of Ti
For generic classes, we can do
class C<T extends Number> { ... }
class C_Integer extends C<Integer>{ ... }
caller must use C_Integer instead of C<Integer> to pick the "specialized" version.
On duck typing: Java is more strict in static typing - unless it is a Duck, it is not a duck.
HI,
java Generics it's different from C++ template.
Example:
Java code:
public <T> T sum(T a, T b) {
T newValue = a.sum(b);
return newValue;
}
In java this code don't work because generics base is class java.lang.Object, so you can use only method of this class.
you can construct this methis like this:
public <T extends Number> T sum(T a, T b) {
T newValue = a.sum(b);
return newValue;
}
in this case the base of generics is class java.lang.Number so you can use Integer, Double, Long ecc..
method "sum" depend of implementation of java.lang.Number.
Bye

Java generics and the Number class

I want to create a method that compares a number but can have an input that is any of the subclasses of Number.
I have looked at doing this in the following manner...
public static <T extends Number> void evaluate(T inputNumber) {
if (inputNumber >= x) {
...
}
}
I need to get the actual primative before I can perform the comparison, the Number class has methods to retrieve this for each primative but I want a clean way of selecting the correct one.
Is this possible?
Cheers
The Number API doesn't offer a clean way to get the value; you have have to use instanceof.
One solution is to "fold" the values into two types: long and double. That way, you can use this code:
if( inputNumber instanceof Float || inputNumber instanceof Double ) {
double val = inputNumber.doubleValue();
...
} else {
long val = inputNumber.longValue();
...
}
Note that this only works for the standard number types but Number is also implemented by a lot of other types (AtomicInteger, BigDecimal).
If you want to support all types, a trick is to use BigDecimal:
BigDecimal value = new BigDecimal( inputNumber.toString() );
That should always work and give you the most exact result.
Unfortunately there is no way to get the primitive type from the wrapper type without resorting to if/else blocks.
The problem is that it just wouldn't be possible to implement such a method in a generic way. Here are some seemingly possible approaches which one could expect to find in the Number class:
public abstract X getPrimitiveValue();
This would be nice, wouldn't it? But it's impossible. There is no possible X that could be an abstraction over int, float, double etc.
public abstract Class<?> getCorrespondingPrimitiveClass();
This won't help either, because there is no way to instantiate primitive classes.
So the only thing you can do that is common to all types is to use the longValue() or doubleValue() methods, but either way you are losing information if you're dealing with the wrong type.
So no: the java number hierarchy is just not suited to solve such problems in a generic way.
Methods with <T extends Number> are always trouble, since you can't really do anything on a Number (all the operators are defined for the children). You would need to either do a ton of instanceof for each child of Number and treat that case by casting to the subtype. Or (better I think - that's the way Sun does it) is to just have a method for each child type, possibly taking advantage of boxing/unboxing for operators like +,-,> etc. where that is possible (all wrappers, not for BigInteger/BigDecimal or any custom types).
If it's really just about comparing the argument to another value of the same type parameter then you could do the following (just adding in T x for simplicity)
public static <T extends Number & Comparable<? super Number>> int evaluate(T inputNumber, T x) {
if (inputNumber.compareTo(x) > 0) { ... }
}
in this case you can use an ordinary method without generics
There's always an option to work with unknown data with pattern interfaces. That's how sorts works with Comparator interface. You should create and add as method parameter functional interface Evaluator with evaluate(T number) method and determine evaluation logic out of method. You can also create some examples from helper classes, like Evaluators::IntegerEvaluator which will work for Integers and suggest them to the client.
Sry for my eng

Categories

Resources