# What Java class should I use to represent a Vector?

Does Java have a built-in Vector class suitable for handling collision detection / response? It should have methods like subtract(Vector v), normalize(), dotProduct(Vector v), ...

It seems logical to use java.awt.Rectangle and java.awt.Polygon to calculate collisions. Would I be right to use these classes for this purpose?

I understand collision detection; I'm only wondering what approach to it is idiomatic in Java. I'm new to the language and to application development in general.

• Just implement it yourself... That way you can only have methods that you need :) – Savlon Jun 4 '14 at 10:39

There is no built in math Vector class. You'll have to implement your own or use a library like JScience - its project page is here.

EDIT: As comment below suggested, JScience isn't really designed for gaming application is missing some optimizations. A more game oriented vector math API can be found in libgdx. I imagine it should not be too difficult to extract just the math classes from libgdx.

• JScience's Vector classes are inefficient for game applications where vectors are constantly modified; they don't allow in-place modification or cycle-saving operations like lengthSquared. – Anko Feb 24 '15 at 13:48

The vecmath-package from Java 3D can be used separately from the rest of the project. It allows in-place modification of vectors and has various methods that are convenient and efficient for games (such as lengthSquared, which avoids a √-operation).

vecmath.jar is 312K and works well separately from the rest of Java3D. It may be included under javax.vecmath in some Java distributions, but you can download it at the below link if not.

There is also a Vector3D class in Apache Commons Math.

• I've found the Vector classes in Apache Commons Math to be lacking for game applications: They don't allow in-place modification (instead returning new instances, which performs badly) and they have no methods to get length (inconvenient) or length-squared (convenience and performance penalty for having to undo the sqrt). – Anko Feb 24 '15 at 13:19
• You can get the length (or length-squared) of the vector by calling getNorm() (or getNormSqrt()). – Felix Scheffer Feb 28 '15 at 22:39

I use the Vector2 and Vector3 class from LibGDX (java gamedev library). It has some odd behaviour and you have to be careful when you do calculations with references, but I guess this is the fault of java not the vector implementation. On the other side, the vector class from XNA had some odd behaviour as well when it did come to normalization and I replaced it with another one from another library :)

LibGDX Vector2 Class

I've just starting using Vectorz, and it's great. Fast, in-place transformations, readily available from Maven Central, well documented.