0

I need to write a vector class that accept any primitive number types in Java. My vector class should only accept 2 components. Here is where I am having trouble.

I must write a function that adds two vectors and return a completely new vector.

If anyone knows a solution of allowing my vector class to accepts in primitive types and perform vector operations like Python, please point me in the right direction!

Something like in pseudocode:

 AddVectors( V1, V2): 
     return new Vector( V1.getX + V2.getX, V1.getY + V2.getY)

Here is my some snipped code of my vector class:

public class Vector<T> {

     private T x;
     private T y;

     public Vector(T x, T y){
         this.x = x;
         this.y = y;

     }

    public T getX(){
         return x;
     }

     public T getY(){
        return y;
     }
}
  • 1
    You can't. Generics cannot be used for primitives (e.g. `int`). They *can* be used for the boxed versions (e.g. `Integer`), however there is no general way to add two [`Number`](https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html) objects (which all boxed primitives subclass), so conclusion is: *You can't!* – Andreas Feb 08 '16 at 03:27
  • Do you know any other way in Java where my vector class accepts any type of primitive numbers and perform vector operations?? –  Feb 08 '16 at 03:33
  • Not "any type of primitive", no. But you can implement a `double` version, which can handle any operation that should handle `byte`, `short`, `int`, and `float`. Double only has 53 bits of precision, so it cannot handle all `long` values, but rather than creating a `long` version, I'd suggest a 2nd implementation doing `BigDecimal`, which can handle it all. Or maybe only a `BigDecimal` version. – Andreas Feb 08 '16 at 03:38
  • I will keep that in mind. Thanks. –  Feb 08 '16 at 03:41
  • So there really is no way to try to make Java like Python's duck typing? –  Feb 08 '16 at 03:43
  • That is correct. Java is strongly typed. See http://stackoverflow.com/questions/1079785/whats-an-example-of-duck-typing-in-java – Andreas Feb 08 '16 at 03:47
  • Andreas, look at that valid answer below. SMH... –  Mar 18 '16 at 06:35
  • I'm sorry, but you said "Writing a *Generic* Vector ... that accept any *primitive* number types". That answer is not [*generic*](https://docs.oracle.com/javase/tutorial/java/generics/types.html), and it stores [*boxed*](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html) objects, not [*primitives*](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html), and it will fail if you mix types. – Andreas Mar 18 '16 at 06:49

0 Answers0