Kenoyer130
Kenoyer130

Reputation: 7318

Java datastructure for a list of type and collection of type

I have a collection where each node is either Class A or a collection of Class A.

This is also recursive in that each node in the collection of Class A could be Class A or a collection of Class A.

I am currently just using List and then checking the Object to see if it is Class A or a List of Class A but that seems to defeat the purpose of using generics. I think I need a more tree like structure. Thoughts?

Upvotes: 1

Views: 92

Answers (4)

John B
John B

Reputation: 32969

Consider creating a class (Wrapper<ClassA>) that can hold either an instance of ClassA or a List. Then make your Lists and inner Lists be List<Wrapper<ClassA>>

Upvotes: 1

Amit Deshpande
Amit Deshpande

Reputation: 19185

You should Define class Node Like below

    public class Node {
       List<Node> children = new ArrayList<Node>();
    }

Upvotes: 0

alvonellos
alvonellos

Reputation: 1062

When you instantiate a generic type you're still going to have homogeneous types stored in the collection. The way that you do this, in the real world, is to establish a common medium, a container, or an interface that binds class A and B together. You use the interface to manipulate those objects.

Alternatively, you can treat objects, by default, as a list. See what I mean?

Upvotes: 2

mishadoff
mishadoff

Reputation: 10789

Look at the Composite design pattern.

Upvotes: 5

Related Questions