Writing a Generic Vector (Math) class in Java - java

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;
}
}

Related

How two achieve a two dimesional vector in Java?

I want to make a two-dimensional vector that is holding two numeric values.
As usual vectors (even of different numerical type) should e.g. be addable.
In C++ you can just do something like:
template<typename T>
class vector2d{
T x{0};
T y{0};
public:
template<typename U> vector2d& operator+=(const vector2d<U>& vec){
x += vec.x;
y += vec.y;
return *this;
}
...
template<typename U>
friend class vector2d;
};
But when I try to achieve this in Java I am coming across some problems.
Here is what I tried to do:
class vector2d<T extends Number>{
private T x;
private T y;
public <U extends Number> vector2d add(vector2d<U> vec){
x += vec.x;
y += vec.y;
return this;
}
...
}
But this does not work. It would if i would use Integer or Float or whatever directly (because of Autoboxing). But this seems not to be the case when you just use the Number class directly. As I think there is no other interface that would satisfy the requirements, I am kind of stuck here.
So my question is if there are ways to make this work in Java.
One of possibilities to achieve this, is use BigDecimal class:
class vector2d{
private BigDecimal x;
private BigDecimal y;
public void add(vector2d vec){
x = x.add(vec.x);
y = y.add(vec.y);
}
...
}
But it can reduce performance of your code, as its operations aren't very fast.
You can also keep Number class and use doubleValue always:
class vector2d{
private Number x;
private Number y;
...
public void add(vector2d vec){
x = x.doubleValue() + vec.x.doubleValue();
y = y.doubleValue() + vec.y.doubleValue();
}
}
this will allow use any types of numbers:
vector2d v1 = new vector2d(1, 2.3);
vector2d v2 = new vector2d(1.3, 2);
v1.add(v2);
UPD: As #Jesper has mentioned, instead of Number just double type can be used, which will eliminate need of .doubleValue() invocation. So you have various way to do it.

"this" objects vs non-static objects

Consider this:
public class Test {
public static int numberOfInstances = 0;
public int myInstanceID;
public String myInstanceName;
The static variable doesn't need to be called within an instance, it's available everywhere like this:
Test.numberOfInstances
When creating an instance, I only do this into my constructor:
public Test(int id, String name) {
myInstanceID = id;
myInstanceName = name;
numberOfInstances += 1;
}
I've recently discovered the this keyword and have noted some of its uses:
public Test() {
this(numberOfInstances + 1, "newInstance");
numberOfInstances += 1;
}
From what I've noticed, the this keyword allows you to call another one of the class' constructors. It also allows you to do this:
public Test(int x, int y) {
this.x = x;
this.y = y;
}
With java, I highly disagree with this style; same variable names, and I don't see the point of using this, especially after looking at the docs example. I look at this:
public Test(int a, int b) {
x = a;
y = b;
However, the use of the this keyword isn't necessary; In my code, I have a variables in my class (e.g. xCoordinate) where I don't use the this keyword (it's not static).
What I've been struggling to understand is what the difference is between non-static variables and this variables. Is there a difference? In one of my classes (the Paddle for Pong), I have this:
public class Pong {
public int xCoordinate;
public int yCoordinate;
and so on...
I never use the this keyword anywhere, and the data is stored within it's own instance.
Bottom line, my question is what is the difference between non-static variables and this.variables. Is it a standard coding practice? Why would I ever you the this keyword on non-static variables?
I think you may have almost answered your own question. You provided the function
public Test(int x, int y) {
this.x = x;
this.y = y;
}
However, what do you think would happen if you wrote it this way instead?
public Test(int x, int y) {
x = x;
y = y;
}
Noticed that I removed the this in the second function. Therefore, x and y would just be referring to the local x and y variables. this allows you to specify that you actually want to use the non-static class variables x and y.
If, as is typical, the parameter variable names of a constructor (say x) are the same as fields of the class, then the field names are shadowed by the parameters passed.
this is used in this case to disambiguate: this.x denotes the field x. It makes perfect sense. this means "reference to the current instance".
So, statements like this.x = x; are quite common.
If you still continue to dislike the Java style, and you adopt m_x-style notation for class fields, then you can write m_x = x; in your constructor. As you rightly point out, this is then not required.
this is also used as the notation for delegating constructors, as you point out.
The "this" keyword allows you to difference between method and instance variables:
public class Point {
private int x;
private int y;
public void add(int x, int y) {
this.x += x;
this.y += y;
}
}
There is no this variables. It's just used to tell the compiler that the variable you want to change is the declared field and not the local variable, in case they have the same name.
For the constructor part, this is just a shortcut for classes which have multiple constructors. You can write the code once and just call that from the alternative constructors.
There is also a similiarly used keyword super, which allows you to call methods and constructors of the superclass:
public SomeClass(int x) {
super(x);
super.someMethod(); // even if we would have overridden someMethod(),
// this will call the one from the superclass
}
Here's one instance where you would need the 'this' keyword:
public class Pong {
public int xCoordinate;
public int yCoordinate;
public Pong (int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
}

Constructor overloading same arguments

Suppose I have class with 2 fields: x and y, of type double. Is it possible to define 2 constructors so constructor1 will create object setting its x property to what parameter in constructor tell and y to default and constructor2 vice versa?
public class Test {
private int x;
private int y;
public Test(int x) {
this.x = x;
}
public Test(int y) {
this.y = y;
}
}
I'm trying something like that and I know that it wont work because of overloading rules
No, you can't do that. Typically you'd do something like:
private Test(int x, int y) {
this.x = x;
this.y = y;
}
public static Test fromX(int x) {
return new Test(x, 0);
}
public static Test fromY(int y) {
return new Test(0, y);
}
You might want to consider that pattern (public static factory methods which in turn call private constructors) even when you don't have overloading issues - it makes it clear what the meaning of the value you're passing is meant to be.
No, You cannot have two methods or constructors with the same signature. What you can do is have named static factories.
public class Test {
private int x;
private int y;
private Test(int x, int y) {
this.x = x;
this.y = y;
}
public static Test x(int x) { return new Test(x, 0); }
public static Test y(int y) { return new Test(0, y); }
}
Test x1 = Test.x(1);
Test y2 = Test.y(2);
No, x and y have identical types, so both constructors would have the same type signature and the method resolution is based on parameter type, not name; the compiler has no way of differentiation.
The compiler looks for "Test.Test(int)" regardless of what the name of the parameter is.
The language would need additional feature added, such as named parameters, to do what you want.
If Java ever gets a syntax like C# for property initialization, you'll be able to use that idiom, using a default no-args constructor.
Besides the alternatives of using explicit factory methods, you could pass in a HashMap for your parameters.
public Test(HashMap<string,int> args) {
if(args.containsKey("x"))
x = args.get("x");
if(args.containsKey("y"))
y = args.get("y");
}
But static factory methods are cleaner for most cases. If you need much more, you may need to consider why you need such an idiom in the first place, and revise your class design.

How to deal with JavaDoc comment repetition?

I was wondering what the best way of documenting this potential Point class is:
public class Point {
/* the X coordinate of this point */
private int x;
/* the Y coordinate of this point */
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
My concrete concern lies with the repetition between the x and y attributes and their respective getters and setters, as well with the constructor arguments.
It's not that I'm developing a public API or anything of the likes, it's no problem for me to have a general comment regarding some variable and then having the getter and setter have just the same text, for instance. I'd just like to avoid comment repetition in my own internal code. Is there a way to tie getX() and the int x argument of the constructor to the x attribute, for instance?
Thanks
Is there a way to tie getX() and the int x argument of the constructor
to the x attribute, for instance?
No, not that I'm aware of. What I do:
don't comment getters (or setters) at all
if X needs contextual information and if it somehow represents (part of the) state of the class I document it in the class-level Javadoc only
One obvious convention would be not writing JavaDoc comments for trivial getters.

Java newbie: How to assign current state of object to another, without establishing reference?

Once again, I'm looking for a way to bypass this array problem, how? Is there any way other than clone()?
I'm asking because fighting with clone(), protection and implemention stuff didn't work for me...
//assuming you have proper class and constructor (point(int x, int y))
/*
point 7POINTSARRAY[]=new point[7];
for(int i=0;i<7;i++)
{
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
}
//This won't work, so...
*/
point B = new point(0,0); // You need this.
for(int i=0;i<7;i++){
7POINTSARRAY[i]=B; // And this.
//But I want to read and assign value only,
// not establish a reference, so it can work How?
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x);
Though desired output is A[1].x=1, it's been owerwritten several times, and now A[1].x = 7.
You need to a create a new point for every element of the array if you want them all to reference different objects:
for(int i=0;i<7;i++)
{
point B = new point(0,0); // Put this *inside* the loop
7POINTSARRAY[i]=B; // Now B is a new instance of point
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x); // should now print 1
I haven't changed your code formatting but improving that will make the above clearer and easier to understand.
Sorry but Java works only with references for complex objects. You should use and implement clone() correctly this can't be the problem. clone() is well defined approach.
Typical clone for first level class looks like following
#Override
public Object clone() {
try {
A ans = (A) super.clone();
// do complex stuff
return ans;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
the line
A ans = (A) super.clone();
does default clone, which includes cloning object but not it's members. You should cascade clone for members. Since clone() is a member, it has access to protected members of the parent.
If your parent is Cloneable you should write
#Override
public Object clone() {
A ans = (A) super.clone();
// do complex stuff
return ans;
}
because parent can't throw exception.
For example, if you have point class looking like follows
class point {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
then you should just fix it in the following way
class point implements Cloneable {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
to make it cloneable.
Then you will be able to write
point a = new point(1,2);
point b = (point) a.clone();
and you will get 2 separate copies.
the problem is with the line
7POINTSARRAY[i]=B
which means that each object in 7POINTSARRAY refer (or points) to the same object B.
so when you do inside the loop
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
you actually always changing B.
You should do instead:
for(int i=0;i<7;i++){
7POINTSARRAY[i] = new point(i,i);
}

Categories