Ted Gress
Ted Gress

Reputation: 9

Implementing pointers and arrays ported to Java

I am porting some C++ code over to Java that uses some heavy pointer arithmetic. My problem is the following:

There is a structure built as such that I have implemented as a class:

In the original C/C++ code I have the following assignments,

struct mst_edge
{
    int u, v;
    double w;
}

mst_edge * tree_edges = new mst_edge[size];

int node_l = tree_edges->u;
int node_r = tree_edges->v;

How is it possible to convert this code to java? The second block declares mst_edge as a C/C++ dynamic array. But in the third block of code it uses the tree_edges as a direct pointer.

What would the Java equivalent of this be, considering memory and references are handled directly by Java?

Upvotes: 1

Views: 133

Answers (3)

rgettman
rgettman

Reputation: 178263

A struct in C/C++ is like a class in Java with all its member variables public:

class MstEdge
{
    public int u;
    public int v;
    public double w;
}

You wouldn't normally do that in Java; the member variables would be private, with public accessor methods, but that's closest to a struct.

A pointer to an array in C/C++ is just an array in Java.

MstEdge[] treeEdges = new MstEdge[size];

But take care, in Java, declaring an array means now you have size null elements. Initialize them like this:

treeEdges[0] = new MstEdge();  // and so on for other array positions

Instead of treating a pointer as a direct reference to the first element as in C/C++, in Java you must explicitly refer to the first element.

int nodeL = treeEdges[0].u;
int nodeR = treeEdges[0].v;

Upvotes: 1

Jerry Hoerig
Jerry Hoerig

Reputation: 146

In OO Java you would use getters to retrieve the private member variables. size is whatever value you have defined.

class MstEdge {
    private int u;
    private int v;
    private double w;

    public int getU() {
        return u;
    }

    public int getV() {
        return v;
    }
   .
   .
   .
}


MstEdge [] treeEdges = new MstEdge[size];

int nodeL = treeEdges[i].getU();
int nodeR = treeEdges[i].getV();

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

The Java equivalent is

mst_edge[] tree_edges = new mst_edge[size];

int node_l = tree_edges[0].u;
int node_r = tree_edges[0].v;

Upvotes: 1

Related Questions