Java Vector wrong output

63 views Asked by At

My problem is, when I add for example 3 inputs in Vector and when I display the result I only found the last output.

XMLTable, Table,Column = classes
cols : the vector who contain the problem

Code :

btnSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            XMLTable xt= new XMLTable();
            Table table = new Table();
            Column col = new Column();
            Vector<String> txtF = new Vector<String>();
            Vector<String> comboF = new Vector<String>();
            Vector<Column> cols = new Vector<Column>();
            Component[] comp = columns.getComponents();
            for(Component c : comp){
                if (c instanceof JTextField){
                    txtF.add(((JTextField) c).getText());
                    //col.setName(((JTextField) c).getText());  
                }
                else if(c instanceof JComboBox){
                    comboF.add(((JComboBox<String>) c).getSelectedItem().toString());
                    //col.setType(((JComboBox<String>) c).getSelectedItem().toString());
                }

            }
            for(int i=0; i<txtF.size();i++){
                col.setName(txtF.get(i));
                //System.out.println("NAMEE: "+txtF.get(i));
                col.setType(comboF.get(i));
                //System.out.println("Type: "+comboF.get(i));
                cols.add(col);
            }


            for(int i=0;i<cols.size();i++){                 
                System.out.println("Column : "+i);
                System.out.println("name : "+cols.elementAt(i).getName());
                System.out.println("type : "+cols.elementAt(i).getType());
            }

INPUT :

name : a  Type : String
name : b  Type : Numeric
name : c  Type : String

OUTPUT :

Column : 0
name : c
type : String
Column : 1
name : c
type : String
Column : 2
name : c
type : String
1

There are 1 answers

0
Turing85 On BEST ANSWER

You are adding the same object to cols over and over again since col is always the same object. Keep in mind that you handle objects by references (even though Java is always pass-by-value, if you pass an object to a method, you actually pass the object-reference, not the object itself). To fix this, remove the declaration of Column col = ... in the fifth line and change the second for loop to this:

[...]
for(int i=0; i<txtF.size();i++){
    Column col = new Column(); // Declaration moved to here
    col.setName(txtF.get(i));
    //System.out.println("NAMEE: "+txtF.get(i));
    col.setType(comboF.get(i));
    //System.out.println("Type: "+comboF.get(i));
    cols.add(col);
}
[...]

This should fix your problem.