P45 Imminent
P45 Imminent

Reputation: 8591

A typedef in Java, for array types in particular

I'm building a graphing GIO and have the following interface:

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

But I find the fact that I have to use java.awt.geom.Point2D[] particularly loathsome as it will appear in a whole load of other interface functions. What I want to do is:

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 can't extend an array like this, and (ii) I question the wisdom of creating a dummy class just to model a language feature (the C++ typedef) that Java doesn't have.

Am I missing something here? Perhaps something with generics but then I effectively lose all type information.

Upvotes: 3

Views: 721

Answers (3)

Mureinik
Mureinik

Reputation: 311843

Java doesn't have typedefs. Although this won't be syntactically different, you can save some text-bloat by using imports (which most modern IDEs collapse 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 really 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();
    ...
}

Upvotes: 4

Braj
Braj

Reputation: 46861

Favor Composition over Inheritance

public class LayerType{

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

And use

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

Note: better use List<Point2D> instead of Point2D[] if the size of array is variable and not known in advance.

Upvotes: 3

Puce
Puce

Reputation: 38142

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 to use JavaFX instead of AWT/ Swing.

Upvotes: 3

Related Questions