我有两个列表: 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语句中,当j>=list2.size()或i>=list1.size()时,不应该判断后一个条件,但JAVA编译器似乎都判断了它们并抛出了IndexOutOfBoundsException,我怎么能让java不执行后条件判断呢?提前感谢!
发布于 2013-05-06 19:27:44
当您想合并两个大小不同的列表时,最小列表的索引总是比最大列表更早完成迭代,因此您必须使用&&运算符。
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++;
}因此,为了进行优化,如果假设list1中有m元素,list2中有n元素,则时间复杂度始终为O(m+n),只会执行两个while循环
编辑
OR和AND运算符是Binary Operators,这意味着它们必须检查它们组合的两个条件,而Not是一元的,它总是需要一个条件来检查..
如果你听说过这些运算符的真值表,所以编译器被编程为基于这些真值表工作,当他看到|| (或运算符)时,他会用OR的真值表检查条件,当他看到&& (and运算符)时,他会用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是状态(条件),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为false
if (A || B)
// some code here在这种情况下,它取决于条件B,如果B为假,则不会执行代码,如果B为真,则将执行代码。
我知道你问为什么如果A为真,它仍然在检查B条件,所以这是因为OR是一个二元运算符。
https://stackoverflow.com/questions/16397527
复制相似问题