Fedour
Fedour

Reputation: 387

Get element of list recursively

I'm working on a project and I've faced the following problem.

I have a Client object which contains an ArrayList<Client> linked attribute. A Client can be link to other Client. The linked Client of Client are stored in this list ( Which form a sort of a graph).

I would like to make a method which can return all client thanks to a recursive call on the linked attribute.

This is my code:

public class Client implements Serializable{        

    String name;
    String ipAddress;
    ArrayList<Client> linked;       

    //Constructor
    public Client(String name, String ipAddress)
    {
        this.name=name;
        this.ipAddress=ipAddress;
        linked=new ArrayList<Client>();
    }

    public void addInList(Client c)
    {
        linked.add(c);
    }
}

My recursiv method is:

public ArrayList<Client> getAllClient(ArrayList<Client> list)
{        
    for(Client c : linked)
    {
        if(!linked.contains(c))
        {
            linked.add(c);
            getAllClient(list);
        }
    }
    return list;
}

I know it is a basic problem but I can not find a solution. What is the best way to do this ?

Upvotes: 0

Views: 1011

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Add a parameter as outputList to be able to track the clients already added to the list within the recursion. It will add all the original clients and all the clients linked to the original list and so on.

public ArrayList<Client> getAllClients(List<Client> outputList, List<Client> list) {
    for (Client client : list) {
        if (!outputList.contains(client)) {
            getAllClients(outputList, client.getLinked());
            outputList.add(client);
        }
    }
    return outputList;
}

Upvotes: 1

Related Questions