I'm attempting implement the add method mentioned in the Generic sparse matrix addition question
class Matrix<T extends Number>
{
private T add(T left, T right)
{
if (left instanceof Integer)
{
return new Integer(((Integer)left).intValue() + ((Integer)right).intValue());
}
}
The compiler errors with found java.lang.Integer Required T at the line where I return a new Integer. I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number.
The compiler doesn't let you do this because T might be some other class, such as Double.
You know that T is Integer from the instanceof check, but the compiler doesn't.
Java's type system is simply not capable of expressing this. Here is a work around.
Create an interface Numeric that provides the numeric operations you are interested in, and write its implementations for the data types you are interested in.
interface Numeric<N> {
public N add(N n1, N n2);
public N subtract(N n1, N n2);
// etc.
}
class IntNumeric extends Numeric<Integer> {
public static final Numeric<Integer> INSTANCE = new IntNumeric();
private IntNumeric() {
}
public Integer add(Integer a, Integer b) {
return a + b;
}
public Integer subtract(Integer a, Integer b) {
return a - b;
}
// etc.
}
And rewrite your Matrix class constructor to accept this implementation.
class Matrix<N> {
private final Numeric<N> num;
private final List<List<N>> contents;
public Matrix(Numeric<N> num) {
this.num = num;
this.contents = /* Initialization code */;
}
public Matrix<N> add(Matrix<N> that) {
Matrix<N> out = new Matrix<N>(num);
for( ... ) {
for( ... ) {
out.contents.get(i).set(j,
num.add(
this.contents.get(i).get(j),
that.contents.get(i).get(j),
)
);
}
}
return out;
}
}
// Use site
Matrix<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE);
Hope that helps.
"I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number."
This statement is false. In general if you have:
public class B extends A {
}
public class C extends A {
}
it does not mean that B can be cast to C. So writing something like:
public <T extends A> T method(T arg) {
return (B)arg;
}
and you calling it with B b = (B)method(C); is obviously wrong.
package generics;
public class Box<T> {
public T j,k;
int l;
float f;
#SuppressWarnings("unchecked")
public void add(T j,T k) {
this.j = j;
this.k=k;
if(j.toString().contains("."))
{
this.f=Float.parseFloat(j.toString())+Float.parseFloat(k.toString());
} else{
this.l=Integer.parseInt(j.toString())+Integer.parseInt(k.toString());
}
}
public int getInt() {
return l;
}
public float getFloat() {
return f;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<Float> floatBox = new Box<Float>();
integerBox.add(new Integer(10),new Integer(20));
floatBox.add(new Float(2.2),new Float(3.3));
System.out.printf("Integer Value :%d\n\n", integerBox.getInt());
System.out.printf("float Value :%f\n", floatBox.getFloat());
}
}
Related
For symbolic representation of mathematical expressions, I am trying to build a hierarchy of number system classes.
In addition to Integer and Real, I also need classes like Rational and Complex. I want all of these classes to inter-operate seamlessly with each other.
e.g. Adding a Complex number to an Integer would give a Complex number etc.
I made all of them to implement the Number interface. (NOT java.lang.Number)
For being able to add numbers of different types, I tried making hierarchy like following.
Integer extends Rational extends Real extends Complex
This makes an Integer to unnecessarily store imaginary part etc. This overhead is undesired.
Also allowing access to imaginary part of an Integer seems improper.
Can anyone suggest a better design where overhead is avoided and interoperation is still possible?
I'd rather create an interface that has something like getRealPart() and getImaginaryPart(). Then your integer can simply return 0 for getImaginaryPart(). That since you want Integer to "be" a Complex, but you don't want Integer to contain the internal implementation of Complex.
public interface Numberr {
public Numberr plus(Numberr n);
public Numberr minus(Numberr n);
public Numberr multiply(Numberr n);
public Numberr sqrt();
...
public Class<? extends Numberr> getType();
}
/////////////////////////////////////////////
public class Integerr implements Numberr {
protected BigInteger value;
#Override
public Numberr plus(Numberr n) {
if (n instanceof Integerr) {
return value.add(n.value);
} else {
// in case of more broad argument type, use method of that class
return n.plus(this);
}
}
....
}
///////////////////////////////////////////////
public class Rational implements Numberr {
protected BigInteger numerator;
protected BigInteger denominator;
#Override
public Numberr plus(Numberr n) {
if (n instance of Integerr) {
return new Rational(numerator.multiply(n.value), denominator);
} else if (n instanceof Rational) {
return new Rational(numerator.multiply(n.denominator).add(n.numerator.multiply(denominator)), denominator.multiply(n.denominator));
} else {
return n.plus(this);
}
}
....
}
I don't see a problem here. Real number is a complex number, integer is a real number. Complex number can be expressed as a + bi and an integer is a complex number, such that a is an integer and b = 0. So every integer has b and it is equal to 0.
You may however consider using composition (and interfaces) over inheritance:
interface Complex {
Real a();
Real b();
}
interface Real extends Complex {
#Override
default Real b() {
return new Integer(0);
}
}
class Integer implements Real {
public Integer(int value) {
// ...
}
#Override
public Real a() {
return this;
}
// ...
}
The disadvantage of this approach is that Integer class can override b() method, so maybe inheritance would be better, because you can use final keyword on the method:
abstract class Complex {
abstract Real a();
abstract Real b();
}
abstract class Real extends Complex {
#Override
public final Real b() {
return new Integer(0);
}
}
class Integer extends Real {
public Integer(int value) {
// ...
}
#Override
public Real a() {
return this;
}
// ...
}
I have tried to model it myself and I came up with this terrible code below. I am not happy about it, because of the following problems:
Interface - InterfaceImpl antipattern
IntegerNumber has methods such as realPart() or numerator() and denominator()
some numbers (complex and rational) use other numbers, while others (real and integer) use Java primitives
Code:
public class Test {
public static void main(String[] args) {
ComplexNumber complexOne = new ComplexNumber(new RealNumber(1.25), new RealNumber(3));
ComplexNumber complexTwo = new ComplexNumber(new RealNumber(7), new RealNumber(18.875));
System.out.println("adding two complex numbers:");
System.out.println(complexOne.add(complexTwo));
RealNumber realOne = new RealNumber(15.125);
RealNumber realTwo = new RealNumber(7.375);
System.out.println("adding two real numbers:");
System.out.println(realOne.add(realTwo));
System.out.println(realTwo.add(realOne));
System.out.println("adding complex and real number:");
System.out.println(complexOne.add(realOne));
System.out.println(realOne.add(complexOne));
RationalNumber rationalOne = new RationalNumber(new IntegerNumber(1), new IntegerNumber(2));
RationalNumber rationalTwo = new RationalNumber(new IntegerNumber(1), new IntegerNumber(3));
System.out.println("adding two rational numbers:");
System.out.println(rationalOne.add(rationalTwo));
IntegerNumber integerOne = new IntegerNumber(6);
IntegerNumber integerTwo = new IntegerNumber(7);
System.out.println("adding two integers:");
System.out.println(integerOne.add(integerTwo));
System.out.println("adding real number and integer:");
System.out.println(integerOne.add(realOne));
System.out.println(realOne.add(integerOne));
System.out.println("adding complex number and integer:");
System.out.println(integerOne.add(complexOne));
System.out.println(complexOne.add(integerOne));
}
}
// interfaces
interface Complex {
Real realPart();
Real imaginaryPart();
default Complex add(Complex other) {
return new ComplexNumber(
this.realPart().add(other.realPart()),
this.imaginaryPart().add(other.imaginaryPart())
);
}
}
interface Real extends Complex {
double asDouble();
#Override
default Real imaginaryPart() {
return new IntegerNumber(0);
}
default Real add(Real other) {
return new RealNumber(this.asDouble() + other.asDouble());
}
}
interface Rational extends Real {
Integer numerator();
Integer denominator();
#Override
default Real realPart() {
return new RealNumber(1.0d * numerator().asInt() / denominator().asInt());
}
#Override
default double asDouble() {
return realPart().asDouble();
}
default Rational add(Rational other) {
return new RationalNumber(
this.numerator().multiply(other.denominator()).add(this.denominator().multiply(other.numerator())),
this.denominator().multiply(other.denominator())
);
}
}
interface Integer extends Rational {
int asInt();
#Override
default Integer numerator() {
return new IntegerNumber(asInt());
}
#Override
default Integer denominator() {
return new IntegerNumber(1);
}
default Integer add(Integer other) {
return new IntegerNumber(this.asInt() + other.asInt());
}
default Integer multiply(Integer other) {
return new IntegerNumber(this.asInt() * other.asInt());
}
}
// implementations
class ComplexNumber implements Complex {
private final Real realPart;
private final Real imaginaryPart;
public ComplexNumber(Real realPart, Real imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
#Override
public Real realPart() {
return realPart;
}
#Override
public Real imaginaryPart() {
return imaginaryPart;
}
#Override
public String toString() {
return String.format("%s + %si", realPart, imaginaryPart);
}
}
class RealNumber implements Real {
private final double value;
public RealNumber(double value) {
this.value = value;
}
#Override
public Real realPart() {
return this;
}
#Override
public double asDouble() {
return value;
}
#Override
public String toString() {
return "" + value;
}
}
class RationalNumber implements Rational {
private final Integer numerator;
private final Integer denominator;
public RationalNumber(Integer numerator, Integer denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
#Override
public Integer numerator() {
return numerator;
}
#Override
public Integer denominator() {
return denominator;
}
#Override
public String toString() {
return String.format("%s/%s", numerator, denominator);
}
}
class IntegerNumber implements Integer {
private final int value;
public IntegerNumber(int value) {
this.value = value;
}
#Override
public int asInt() {
return value;
}
#Override
public String toString() {
return "" + value;
}
}
I am wondering whether interfaces should be abstract classes with implemented methods being final. In the end, I think it may be better to just go with simple inheritance and ignore the fact that every integer will have a field for imaginary part.
I hope this will give you some ideas.
Is there a way in Java to implement this method?
public static <T extends Number> T doubleOf(T number){
//I don't know...
}
Thanks
As mentioned in other answers, there is no general solution.
Beside others, the operation you want to implement may not be well defined for some Number subclasses. For instance, what is the multiple of AtomicInteger? Is it the same instance with a multiplied value? Or a new instance of AtomicInteger? Or a new plain Integer? Theoretically, there might be a subclass of Number that does not allow to create new instances freely.
You may test the input for some known subclasses and implement the operation for those. Something like this:
#SuppressWarnings("unchecked")
public static <N extends Number> N multiply(N number, int multiplier) {
Class<? extends Number> cls = number.getClass();
if (cls == Integer.class) {
return (N) Integer.valueOf(number.intValue() * multiplier);
}
if (cls == Long.class) {
return (N) Long.valueOf(number.longValue() * multiplier);
}
throw new UnsupportedOperationException("unknown class: " + cls);
}
I am afraid the suppression of warnings will be necessary, in some form.
Unfortunately it is not possible in Java because you can't instantiate an object of type T.
See this section of the Java generics tutorial: http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects
A little bit late, but today i had this same problem.
My solution:
public Number multiply(Number number, int multiplier) {
return new Number() {
#Override
public long longValue() {
return number.longValue() * multiplier;
}
#Override
public int intValue() {
return number.intValue() * multiplier;
}
#Override
public float floatValue() {
return number.floatValue() * multiplier;
}
#Override
public double doubleValue() {
return number.doubleValue() * multiplier;
}
};
}
Simple answer is no. Number have no appropriate methods.
But as long as Number have several well known implementation you can just implement it for all of them. Of course if someone create new one you implementation will fail but it is very unlikely
public static <T extends Number> T doubleOf(T number){
if(number instanceOf Integer){
return (T)(Object)number.intValue()*2;
} ... and so on
}
Although a bit weird, you could use the following:
public static <T extends Number & Multipliable> T doubleOf(T number)
{
}
interface Multipliable<T extends Number>
{
T multiply(Number number);
}
class MyDouble extends Number implements Multipliable<MyDouble>
{
Double d;
public MyDouble(final double d)
{
this.d = new Double(d);
}
#Override
public MyDouble multiply(Number number)
{
return new MyDouble(d.doubleValue() * number.doubleValue());
}
#Override
public double doubleValue()
{
return d.doubleValue();
}
#Override
public float floatValue()
{
return d.floatValue();
}
#Override
public int intValue()
{
return d.intValue();
}
#Override
public long longValue()
{
return d.longValue();
}
}
This could be used like this:
MyDouble result = new MyDouble(2d).multiply(new Short((short) 1));
So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}
Imagine I have a class
class A {
int a;
int b;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
return 0;
}
void setTheFunction([...]) {
[...]
}
}
And for every new object I instantiate, I want to be able to define theFunction() in a new way by calling setTheFunction( [...] ). For example, I want to do something like this:
A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Or something like this:
A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Now, what I could of course do is write all of those functions inside class A and use a switch statement to determine which one is to pick. But if I don't want the algorithm of theFunction() hardcoded inside my class A, is there any way to do something similar to the above? And what would setTheFunction() look like? What type of argument would you have to pass?
You can use Callable.
public class A<V> {
public int a;
public int b;
private Callable<V> callable;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public V theFunction() {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setTheFunction(Callable<V> callable) {
this.callable = callable;
}
}
Then, to use it:
final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
int x = test.a * test.b;
return x * x + 2;
});
System.out.println(test.theFunction());
Of course, the generic typing of A isn't necessary, but I've added it to make this answer to be less restricted.
If you always need to operate on the same arguments, you could solve this by defining an interface such as:
public interface MethodPerformer {
int performOperation(int a, int b);
}
Then pass in implementations of this to your setTheFunction method. Finally, invoke the operation when you call the other method:
class A {
int a;
int b;
MethodPerformer performer;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
performer.performOperation(a, b);
}
void setTheFunction(MethodPerformer performer) {
this.performer = performer;
}
}
Clearly additional code would be required to check the performer is not null. Perhaps take a performer in the constructor?
Instead of using a setter, the more natural way is to use an anonymous sub-class. This way the compiler will check it behaves correctly and has access to the right variables.
public class Main {
static abstract class A {
protected int a, b;
A(int a, int b) {
this.a = a;
this.b = b;
}
public abstract int theFunction();
}
public static void main(String... ignored) {
A test = new A(3, 2) {
#Override
public int theFunction() {
int x = a * b;
return x * x + 2;
}
};
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
A test2 = new A(1, 5) {
#Override
public int theFunction() {
for (int i = 1; i < b; i++) a = a * b * i;
return a;
}
};
System.out.println(test2.theFunction());
}
}
prints
38
15000
With this you can solve any kind of problem, that involves any kind of public variable of A (but can work with package private variables as well, if the AFunction implementation resides in the same package), that a function may use to perform it's operation. It's just not as compact as it can be in other languages than java.
interface AFunction
{
int call(A a);
}
class A
{
int a;
int b;
//giving it a default implementation
private AFunction f = new AFunction()
{
#Override
public int call(A a)
{
return a.a * a.b;
}
};
A(int a, int b)
{
this.a = a;
this.b = b;
}
int theFunction()
{
return f.call(this);
}
void setTheFunction(AFunction f)
{
this.f = f;
}
}
By the way as AlexTheo points out, all answers so far (except for Peter Lawrey's) are a form of the strategy design pattern.
The easiest way to do this is defining "A" as an interface instead of a class. You declare theFunction() without actually implementing it.
In client code, everytime you need "A", you instantiate a so-called anonymous inner class.
For example:
new A() { #Override public int theFunction() { ...your implementation... } };
I am trying to write a method in which I need to create a temp variable, sum, of generic type T. However, I'm getting the error "The local variable sum may not have been initialized". How can I initialize a generic variable? I can't set it to 0 or 0.0, and I can't find information anywhere on how to deal with this. Here is the portion of code that I'm working with:
public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException
{
Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize);
T sum, product;
if (rowSize != right.columnSize)
throw new MatrixException("Row size of first matrix must match column size "
+ "of second matrix to multiply");
setup(temp,rowSize,columnSize);
for (int i = 0; i < rowSize; i++){
for (int j = 0; j < right.columnSize; j++) {
product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
sum = arithmetics.add(product, sum);
temp.matrix[i][j] = sum;
}
}
return temp;
}
I'm not sure if this will help clarify, but here is my interface Arithmetics:
public interface Arithmetics<T> {
public T zero();
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And here is one of my classes, DoubleArithmetics, just to show how I'm implementing the interface:
public class DoubleArithmetics implements Arithmetics<Double> {
protected Double value;
public Double zero()
{
return new Double(0);
}
public Double add( Double a, Double b )
{
return new Double(a.doubleValue()+b.doubleValue());
}
public Double subtract (Double a, Double b)
{
return new Double(a.doubleValue()-b.doubleValue());
}
public Double multiply (Double a, Double b)
{
return new Double(a.doubleValue()*b.doubleValue());
}
public Double parseString( String str )
{
return Double.parseDouble(str);
}
public String toString( Double a )
{
return a.toString();
}
}
Just use the zero method that you already have on your interface to initialize sum:
T sum = arithmetics.zero();
For the non-zero initialization, you could also add methods that take long and double values and return the T for them:
public interface Arithmetics<T> {
public T zero();
public T create(long l);
public T create(double d);
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And then implement them:
public Double create(long l) {
return new Double(l);
}
public Double create(double d) {
return new Double(d);
}
And finally, to use them:
T one = arithmetics.create(1);
Instantiating generics in Java is a bit tricky due to type erasure.
My approach is to pass into your generic class' constructor two items: (1) a java.lang.reflect.Constructor specific to type T; and (2) an Object[] array holding a default value specific to type T.
When you later want to instantiate and initialize a type T, you need to call Constructor.newInstance(Object[]). In the code below, the MyGenericClass class stands in for your generic class (looks like it's called Matrix from your original post).
I got the solution from InstantiationException for newInstance() and Create instance of generic type in Java?
public class MyGenericClass<T>
{
Constructor _constructorForT;
Object[] _initialValueForT;
public MyGenericClass(Constructor constructorForT,
Object[] initialValueForT)
{
_constructorForT = constructorForT;
_initialValueForT = initialValueForT;
}
public void doSomething()
{
T sum = initializeT(_constructorForT, _initialValueForT);
System.out.printf("d = %f\n", sum);
}
#SuppressWarnings("unchecked")
private T initializeT(Constructor constructor, Object[] args)
{
T result = null;
try
{
result = (T) constructor.newInstance(args);
}
catch (java.lang.InstantiationException ex)
{
}
catch (java.lang.IllegalAccessException ex)
{
}
catch (java.lang.reflect.InvocationTargetException ex)
{
}
return result;
}
public static void main(String argv[]) throws Exception
{
Constructor constructor =
Double.class.getConstructor(new Class[]{double.class});
Object[] initialValue = new Object[] { new Double(42.0) };
MyGenericClass<Double> myGenericClass =
new MyGenericClass<Double>(constructor, initialValue);
myGenericClass.doSomething();
}
}