简体   繁体   中英

Storing elements into an ArrayList but getting redundancies?

I edited the question: I'm trying to store foreign keys of all tables of a database in an arraylist Fkeys. I have the method getFK that retrieves foreign keys (if they exist) of existing tables

public ArrayList Fkeys = new ArrayList();
public ArrayList Vec = new ArrayList();

public ArrayList getFK () {
    try {

        /* Database connection */

       DBConnection connect = new DBConnection();
       connect.DBConnect();
       Connection con = connect.con;
       /* Getting some infos regarding keys*/
       DatabaseMetaData metadata = con.getMetaData();
       ResultSet clefs = metadata.getImportedKeys(null, null, "persons");

while(clefs.next()) {
    Vec.add(clefs.getString("FKCOLUMN_NAME"));
                   }
    Fkeys.add(Vec);


    clefs = metadata.getImportedKeys(null, null, "departments");

while(clefs.next()) {
    Vec.add(clefs.getString("FKCOLUMN_NAME"));
                   }
    Fkeys.add(Vec);
}

Now when I execute this I get this result : [[ ], [ ]] because the two tables persons and departments have no foreign key. But when I add these lines to the method regarding the table students which has 3 foreign keys

clefs = metadata.getImportedKeys(null, null, "students");

while(clefs.next()) {
    Vec.add(clefs.getString("FKCOLUMN_NAME"));
                   }
    Fkeys.add(Vec);

I get this result : [[id, person, depp], [id, person, depp], [id, person, depp]] While it is supposed to be: [[id, person, depp], [ ], [ ]] What I'm doing wrong? and why the content of Vec is stored in all positions of Fkeys?

This loop seems to be adding the same thing to alist each time ...

    while(keys.next()) {
          alist.add(clefs.getString("FKCOLUMN_NAME"));  
    }

I can't be sure this this is the problem ('cos you don't tell us what clefs is!) ... but it looks mighty suspicious to me.

Check out Sets , they're like Lists, but they have the ability to be unique inside the object. Ie if you have:

Set<Integer> intSet = new HashSet<Integer>()
intSet.add(1);
intSet.add(1);
for (Integer i : intSet) {
     System.out.println(i);
}

The final output should be:

1

Sets don't allow multiple Identical Objects in the same set.

Also, When you were declaring your ArrayLists, be sure to note what kind of an ArrayList each one is, otherwise your IDE should be yelling at you, but I think it defaults to Object. I recommend having a custom model object if you need 3 fields in the Set/List and declare it like this List<CustomModelObject> listOfObjects = new ArrayList<CustomModelObject>(); (see above example if you need an example for Set)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM