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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...