Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

complicated abstract class question

  Asked By: Erica    Date: Apr 14    Category: Java    Views: 730
  

I have the following classes

abstract class O{...}

class A extends O{...}
class B extends O{...}

class foo{
O bar;
...
}

Now, I have a list L of instances of A and B. I want to create a list
of instances of foo where each instance has a copy of one of the
objects in L, as I will be messing with the objects but want to keep
the original data.

Normally, I'd do something like: (yes, I should be using an iterator)

O x;
while(x = (O)(L.next))
fooList.add(new foo(x));

The problem I'm running into is that since everything is a reference,
I need to create a copy of each object I pass into the foo constructor
or I'll be messing with the original. Since I don't know what the
actual class for each object is, I can't create a new object of the
proper class, so I have to use the superclass.

I kludged a solution by copying the initial list and pointing the
fooList at it. Is there a nicer way to do this, or am I missing
something fundamental?

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Orville Rodriguez     Answered On: Apr 14

You could subclass the List and and over ride the add
method to create  a new instance  of the object  that was
passed in then passing that object to super.add(...).

 
Answer #2    Answered By: Bonifaco Garcia     Answered On: Apr 14

You should implement Cloneable, override the clone() method and then
call that. You don't need to know the type of the object  since the
clone() method is defined in the Object class. Take a look at
java.lang.Object's clone() method for more information.

 
Didn't find what you were looking for? Find more on complicated abstract class question Or get search suggestion and latest updates.




Tagged: