Re: ArrayList implementation
Can't you just use an ArrayList of A?
ArrayList<A> list = new ArrayList<A>();
Re: ArrayList implementation
Quote:
Originally Posted by
KevinWorkman
Can't you just use an ArrayList of A?
ArrayList<A> list = new ArrayList<A>();
Then how will the get method now whether to return an object of the type B or C?
Re: ArrayList implementation
Quote:
Originally Posted by
meijuh
Then how will the get method now whether to return an object of the type B or C?
It won't. It'll return an A reference, which you can cast to the appropriate type. If you really need to be able to return a B or C from an ArrayList, you're going to have to keep track of two ArrayLists.
Re: ArrayList implementation
Quote:
Originally Posted by
KevinWorkman
It won't. It'll return an A reference, which you can cast to the appropriate type. If you really need to be able to return a B or C from an ArrayList, you're going to have to keep track of two ArrayLists.
But this means I need to implement MyArrayList two times for exactly the same functionality. Is there no other way?
I believe type casting indicates a bad design...
Re: ArrayList implementation
Why do you need to extend ArrayList in the first place?
If you need to keep track of two separate types (as opposed to simply keeping track of a single parent type), then you either need two ArrayLists or you need to cast. Simple as that. You said you only need the methods from class A. So why do you care whether something is a B or C?
Re: ArrayList implementation
When adding an element to the ArrayList I know that it is either a B or a C. Before actually adding it I need to check if that B or C is already contained by the ArrayList. So ArrayList.add() which I want to override must invoke a ArrayList.contains or something.
Hmm... looking at the documentation of ArrayList the method add may not return false. So I can not know if it is added or not.
I think I need to think a little more about the design.
Re: ArrayList implementation
Why don't you just use a Set?
Re: ArrayList implementation
I moved responsibility from the list to the B and C class. Now the list does not need to know whether the A is in fact a B or C. So this question is no longer relevant.
Thanks for your help Kevin.