Nir
Nir

Reputation: 2629

How to build an array recursively

I want to build an array recursively I started this way and cant figure how to do it properly:

public class ConnectivityNode {
  private Server server;
  private ConnectivityNode parent;
  private ArrayList<ConnectivityNode> children;

...

  public Server[] getServerRoute(){
    if(this.parent == null) { return null; }
    return this.server + this.parent.getServerRoute(); //of course this isnt correct
  }
}

The idea is to get an array of Servers

{ parent.parent.server1, parent.server2, server3 }

Upvotes: 0

Views: 763

Answers (4)

user902383
user902383

Reputation: 8640

if i understand you correcty, and you want to obtain route from current element to root element in your tree, it will be something like that:

public Server[] getServerRoute(){
    List<Server> servers=new ArrayList<>();
    walk(this,servers);
    return servers.toArray(new Server[servers.size()]);
  }

private static void walk(ConnectivityNode node,List<Server> servers)
{
servers.add(node.getServer());
if (node.getParent() != null)
{
walk(node.getParent(),servers);
}

}

Upvotes: 0

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

Use an ArrayList:

There are two ways to do this. If you have to return an array, you can use:

public Server[] getServerRoute()
{
    if(this.parent == null) 
    { 
         return null; 
    }

    ArrayList<Server> servers = new ArrayList<Server>();
    servers.add(this.server);
    servers.addAll(Arrays.asList(this.parent.getServerRoute()));

    return servers.toArray(new Server[0]);
}

If it's okay to just return an ArrayList (which can trivially be converted into an array, just as we did above), it would be make the function simpler:

    public ArrayList<Server> getServerRoute()
    {
        if(this.parent == null) 
        { 
             return null; 
        }

        ArrayList<Server> servers = new ArrayList<Server>();
        servers.add(this.server);
        servers.addAll(this.parent.getServerRoute());

        return servers;
    }

Upvotes: 0

arshajii
arshajii

Reputation: 129497

One option is to work with a List and create a helper function:

private void getServerRouter(List<Server> l) {
    l.add(server);
    if (parent != null) {
        parent.getServerRouter(l)
    }
}

public Server[] getServerRouter() {
    List<Server> l = new ArrayList<>();
    getServerRouter(l);
    return l.toArray(new Server[l.size()]);
}

You might even consider returning the List from the public method (that might make more sense).

Upvotes: 3

RaphMclee
RaphMclee

Reputation: 1623

You will need an function with a parameter. So for example like this:

public void getServerRoute(Server actualServer){
  children.add(actualServer);
  if(actualServer.hasParent())
    getServerRoute(actualServer.getParent());
}

As I do not know how you find the parent of a server I just assumed you have a function for that matter.

Upvotes: 0

Related Questions