Typedef in Java, for array types, in particular

I am creating a graphical GIO and have the following interface:

public interface GraphModel
{
    public java.util.List<java.awt.geom.Point2D[]> getLayers();
    ...
}

      

But I find a fact that I have to use java.awt.geom.Point2D[]

especially disgusting as it will appear in all loading of other interface functions. I want to do this:

public interface GraphModel
{
    public class LayerType extends java.awt.geom.Point2D[]{};
    public java.util.List<LayerType> getLayers();
    ...
}

      

But this is not good, since (i) you cannot expand an array like this, and (ii) I am asking the wisdom of creating a dummy class just to simulate a language feature (C ++ typedef

), which Java does not have.

Am I missing something? Maybe something with generics, but then I actually lose all the type information.

+3


source to share


3 answers


Java doesn't have typedef

s. While it won't be syntactically different, you can save some text bloat by using import

(which destroys most modern IDEs so they don't irritate your eyes):

import java.util.List;
import java.awt.geom.Point2D;

public interface GraphModel
{
    public List<Point2D[]> getLayers();
    ...
}

      



The only option you have is to create a dummy class that wraps the array:

public class MyPoints {
    private Point2D[] myPoints;

    /* constructors, getters, setters, some logic you may have */
}

public interface GraphModel
{
    public List<MyPoints> getLayers();
    ...
}

      

+4


source


Use import statements:

import java.awt.geom.Point2D;
import java.util.List;

public interface GraphModel
{
    public List<Point2D[]> getLayers();
    ...
}

      

also prefer lists over arrays:



import java.awt.geom.Point2D;
import java.util.List;

public interface GraphModel
{
    public List<List<Point2D>> getLayers();
    ...
}

      

And consider using JavaFX instead of AWT / Swing.

+3


source


Use composition over legacy

public class LayerType{

      private Point2D[] points;
      // setter & getter methods
};

      

And use

public interface GraphModel{
    public List<LayerType> getLayers();
    ...
}

      

Note: it is better to use List<Point2D>

instead Point2D[]

if the size of the array is variable and unknown in advance.

+3


source







All Articles