I recently started learning Java, and I decided to implement a basic vector system for another particle system I was building.
import java.util.*; class Vector { int x; int y; public Vector(int x, int y) { this.x = x; this.y = y; } public void add(Vector vector) { this.x += vector.x; this.y += vector.y; } public void sub(Vector vector) { this.x -= vector.x; this.y -= vector.y; } public void mul(Vector vector) { this.x *= vector.x; this.y *= vector.y; } public void div(Vector vector) { this.x /= vector.x; this.y /= vector.y; } } What can be improved? I'm new to Java, so constructive criticism on anything would be nice.
Here's my re-factored code, based on input from as many answers as possible. Thanks for the feedback!
import java.util.*; class Vector { private final double x; private final double y; public Vector(double x, double y) { this.x = x; this.y = y; } public Vector add(Vector other) { return new Vector(x + other.x, y + other.y); } public Vector sub(Vector other) { return new Vector(x - other.x, y - other.y); } public double scalar(Vector other) { return x * other.x + y * other.y; } public double lengthSq() { return x*x+y*y; } public double length() { return Math.sqrt(lengthSq()); } public double distSq(Vector other) { double dx = x - other.x; double dy = y - other.y; return dx*dx+dy*dy; } public double distance(Vector other) { return Math.sqrt(distSq(other)); } }