0

我有两个列表:list1,list2。我遍历两个列表并将它们组合成一个列表。然后我使用这样的声明:

if(list1 != null && list2 != null)
{
  int i=0,j=0;     
 while(i<list1.size() || j<list2.size())   
{

if((j>=list2.size()) || (curFormater.parse(list1.get(i).RecordDate).compareTo(curFormater.parse(list2.get(j).RecordDate)) < 0))                {
    .....                   
i++;      

    }
    else if((i>=list1.size()) || (curFormater.parse(list1.get(i).RecordDate).compareTo(curFormater.parse(list2.get(j).RecordDate)) < 0))
    {
    .....


j++;

}


....

    }

在这两个if语句中,when j>=list2.size()or i>=list1.size(),后面的条件不应该判断,但是JAVA编译器似乎都判断它们并抛出IndexOutOfBoundsException。我怎样才能让java不执行后面的条件判断?提前致谢!

4

1 回答 1

0

当你想合并两个不同大小的列表时,最小列表的索引总是比最大​​列表更早完成迭代,所以你必须使用&&运算符。

if(list1 != null && list2 != null)
{ 
  int i=0,j=0;     
  while(i<list1.size() && j<list2.size())   
  {
      // your code
      i++; 
      j++;
  }
  // when one of them arrived to end of list to loop will not be executed so you need to check
  // those conditions
 while (i > list.size() && j < list.size())
 {
       // your code
       j++;
 }
 while (i < list.size() && j > list.size())
 {
       // your code
      i++;
 }

所以为了优化,如果假设mlist1中有n元素,list2中有元素,时间复杂度总是O(m+n),只会执行两个while循环

编辑

ORAND运算符 are Binary Operators,这意味着它们必须检查它们组合的两个条件,而Notis Unary 总是需要一个条件来检查。
如果您听说过这些运算符的真值表,那么编译器被编程为基于这些真值工作表,当他看到 || (或运算符)他用 OR 的真值表检查条件,当他看到 && (和运算符)时,他用 AND 的真值表检查条件。并且由于 OR 和 AND 都是二元运算符,这两个条件都将被“判断”,即使其中一个为真。

或真值表

(假设 A 和 B 是语句(条件),而 R 是您对它们执行 OR 时的结果

-------------------------
   A   |   B   |  R 
------------------------- 
  True | True  |  True  
-------------------------
  True | False |  True  
-------------------------
  False| True  |  True
------------------------- 
  False| False |  False
-------------------------  
 // so in Or table, when both of the conditions are false the result is False
 // while when one of them is true the result is True

和真值表

(假设 A 和 B 是 statemnts (条件),R 是你做 And 时的结果

-------------------------
   A   |   B   |  R 
------------------------- 
  True | True  |  True  
-------------------------
  True | False |  False  
-------------------------
  False| True  |  False
------------------------- 
  False| False |  False
-------------------------  
// so in And table, when both of the conditions are true the result is True
// while when one of them is false the result is False

我希望现在你明白为什么即使其中一个为真,也必须检查这两个条件。例如,假设你有两个条件 A 和 B,你对它们执行 OR 并假设 A 为假

if (A || B)
// some code here

在这种情况下,它取决于条件 B,如果 B 为假,则不会执行代码,如果 B 为真,则将执行代码。

我知道你问为什么如果 A 为真,它仍在检查 B 条件,所以这是因为 OR 是二元运算符。

于 2013-05-06T11:27:44.173 回答