Code duplication caused by primitive types: How to avoid insanity?

前端 未结 8 458
温柔的废话
温柔的废话 2020-12-13 00:44

In one of my Java projects I am plagued by code repetition due to the way Java handles (not) primitives. After having to manually copy the same change to four different loca

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 01:01

    From the performance point of view (I make a lot of CPU-bound algorithms too), I use my own boxings that are not immutable. This allows using mutable numbers in sets like ArrayList and HashMap to work with high performance.

    It takes one long preparation step to make all the primitive containers with their repetitive code, and then you just use them. As I also deal with 2-dimensional, 3-dimensional etc values, I also created those for myself. The choice is yours.

    like:
    Vector1i - 1 integer, replaces Integer
    Vector2i - 2 integer, replaces Point and Dimension
    Vector2d - 2 doubles, replaces Point2D.Double
    Vector4i - 4 integers, could replace Rectangle
    Vector2f - 2-dimensional float vector
    Vector3f - 3-dimensional float vector
    ...etc...
    All of them represent a generalized 'vector' in mathematics, hence the name for all these primitives.

    One downside is that you cannot do a+b, you have make methods like a.add(b), and for a=a+b I chose to name the methods like a.addSelf(b). If this bothers you, take a look at Ceylon, which I discovered very recently. It's a layer on top of Java (JVM/Eclispe compatbile) created especially to address it's limitations (like operator overloading).

    One other thing, watch out when using these classes as a key in a Map, as sorting/hashing/comparing will go haywire when the value changes.

提交回复
热议问题