Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

java - List of String Arrays overwriting itself

First ever question here, complete newbie so try to take it easy on me. I'm trying to figure out what's wrong here:

public List<String[]> idOnlyQuery(String searchTerm, Connection conn){

    List<String[]> result = new ArrayList<String[]>();
    String[] rowResult = new String[7];

    Statement stmt = null;      
    try {
      stmt = conn.createStatement();
      ResultSet rs = stmt.executeQuery( "SELECT * FROM Jets WHERE CurrentID LIKE '" + searchTerm + "%'");
      while(rs.next()){

          String currentId= rs.getString("CurrentId");
          String manufacturer = rs.getString("Constructor");
          String type = rs.getString("ACType");
          String series = rs.getString("Series");
          String index = rs.getString("KeyNo");
          String operator = rs.getString("Operator");
          String baseAirport = rs.getString("Home_Airfield");
          rowResult[0] = (currentId);
          rowResult[1] = (manufacturer);
          rowResult[2] = (type);
          rowResult[3] = (series);
          rowResult[4] = (operator);
          rowResult[5] = (baseAirport);
          rowResult[6]= (index);
          result.add(rowResult);
      }
    System.out.println(result.get(0)[0]);

This method returns a list of string arrays, these arrays are retrieved from an SQLite database. Everything works apart from the fact that the string arrays in my result List seem to be getting overwritten every time the while loop repeats itself. The last println always gives me the currentId of the last row retrieved from the database, but if I put a println inside the while loop it returns the appropriate data on each while cycle. I really can't figure out where my String[] elements are getting overwritten. It's probably really obvious but I've spent hours looking online to check if I'm doing the add procedure correctly and still no joy. HELP!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to create the rowResult array in the loop. Your list just holds a pointer to the array and you are basically only working with one instance all the time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...