I have a class with several member variables, one of which is a DefaultTableModel. My constructor for the class uses a MySQL ResultSet to populate the DefaultTableModel. I would like to generate an exact copy of the DefaultTableModel and store it as another member variable within my class, so I can edit a copy of the variable within my class while maintaining a copy of the original variable.
Below is an outline of my class.
public class MyClass() {
int i;
Boolean b;
DefaultTableModel model;
DefaultTableModel model2;
MyClass(ResultSet myRS) {
//code to initialize i,b,model;
//code to clone model and save as model2;
//code to modify model2;
}
public DefaultTableModel getModels(String s) {
//code that returns model or model2;
}
}
I have been doing some reading but haven't figured out how to make an exact copy of a variable within a class. I know I can't just do model2 = model;
since this just copies the references of the variable. I made this mistake and found out that editing model2 would also edit model. Everything I have read about clone makes it seem that it is just used to make a new and identical instance of an entire class. Any advice on how to clone a single variable within a class would be greatly appreciated.
Normally if it was your own TableModel subclass rather than DefaultTableModel
you could achive this by making your TableModel
implement Clonable
and get a copy by calling the clone()
method.
As you are working with DefaultTableModel
instances, you have to go the other way around and do this:
Instead of creating a single Object[][]
or Vector
instance for passing data to the constructor of DefaultTableModel
, create two copies of Object[][]
or Vector
. With these you can create both DefaultTableModel
instances with the same content.