0

在下面的代码片段中,我执行一个查询并将结果集传递给set. 然后将set分配给set1。之后有一个 while 循环,一直持续到set.next返回false。是否如果set.next在循环后返回 false ,set1也会返回 false ?

ResultSet set = statement.executeQuery();
ResultSet set1 = set;
while (set.next()) {
    if (set.getString(1).equalsIgnoreCase(keyword)) { 
        // If the search matches the exact keyword
        list.put(set.getString(2), set.getString(1));
        // Where key is the name of the node and value is, name of the file
    }
}

我问这个是因为:

while (set1.next()) {
    System.out.println("@@@Inside the while statement@@@");
    if (set1.getString(1).contains(keyword) 
    && set1.getString(1).compareToIgnoreCase(keyword) !=0) { 
        // If the search contains the keyword but does not exactly match
        list.put(set.getString(2), set.getString(1));
        // Where key is the name of the node and value is, name of the file
        System.out.println("@@@Inside the if statement of second while loop !@@@");
    }
}

这种while构造永远不会起作用。是这个原因吗?如果是这样,我该怎么办?

4

4 回答 4

1

您有两个主要错误:

  1. 分配setset1不会复制 - 它是同一组
  2. String.contains()区分大小写(您的代码与您的注释不匹配)

修复方法是:

  1. 不要使用两个循环 - 只使用一个循环
  2. 使用`toLowerCase()withcontains()实现“不区分大小写的包含”测试
  3. 此外,如果您的第一个测试是真的,那么您的第二个测试也是如此,所以无论如何您都不需要两个测试/循环

试试这个代码:

   ResultSet set = statement.executeQuery();
   while(set.next()) {
       if(set.getString(1).toLowerCase()
              .contains(keyword.toLowerCase)) {
           list.put(set.getString(2), set.getString(1));
       }
   }

另外,不要将地图称为“列表” - 将其称为“地图”,否则只会让代码的读者感到困惑。

于 2013-02-08T18:55:50.720 回答
0

是否如果set.next在循环后返回 false ,set1也会返回 false ?

的。因为指的set1是指的是同一个对象。因此,被引用的对象所表现出的任何行为也将被反映。在你的第一个while循环中,被引用的对象在迭代所有记录后完全耗尽(使用set.next())。此后,无论哪个变量(set 或 set1)尝试读取更多内容,都将得到.ResultsetsetResultSetsetset1ResultSetset.next()false

如果在您的第​​一个 while 循环构造中,我使用变量检查并.next()使用set变量获取结果,set1它仍然可以工作。试试这个代码而不是你的第一个构造,你会看到输出和你在第一个 while 构造中写的一样:

ResultSet set = statement.executeQuery();
       ResultSet set1 = set;
       while(set.next()) {
           if(set1.getString(1).equalsIgnoreCase(keyword)) { // If the search matches the exact keyword
               list.put(set1.getString(2), set1.getString(1));
               // Where key is the name of the node and value is, name of the file
           }
       }

如果您仍想set1返回结果,您应该ResultSet使用以下方法重建一个新对象:

set1 = stat.executeQuery()

在哪里,statStatement/PreparedStatement您在代码中使用的任何内容。

于 2013-02-08T18:28:20.530 回答
0

set1是对指向的同一个对象的引用set。如果你想再次迭代ResultSet,你需要使用类似的方法将迭代器光标再次移动到开头:

set.beforeFirst();

在 Java 中,将变量分配给对象不会复制对象,它只会引用内存中的对象。如果你想独立工作set,你必须明确地制作一个对象的副本。set1

在您的特定用例中,我认为这不是您想要的,只是移动迭代光标似乎更好。

于 2013-02-08T18:25:38.780 回答
0

你可以尝试这样做。

   ResultSet set1 = statement.executeQuery();
于 2013-02-08T18:23:32.030 回答