i have 2 list: list1,list2. traversal 2 list , combine them 1 list. use such statement:
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++; } .... }
in these 2 if-statements, when j>=list2.size()
or i>=list1.size()
, latter condition should not judged,but java compiler seems judge them , throw indexoutofboundsexceptio
n. how can let java not excute latter condition judgement? in advance!
when want merge 2 lists have different size, index smallest list finish iterate earlier largest list, have use &&
operator.
if(list1 != null && list2 != null) { int i=0,j=0; while(i<list1.size() && j<list2.size()) { // code i++; j++; } // when 1 of them arrived end of list loop not executed need check // conditions while (i > list.size() && j < list.size()) { // code j++; } while (i < list.size() && j > list.size()) { // code i++; }
so optimization, time complexity o(m+n) if assume there m
elements in list1 , n
elements in list2, 2 while loops executed
edit
or
, and
operators binary operators
, means must check 2 conditions combine, while not
unary alwyas need 1 condition check..
if heard truth tables of operators, compilers programmed work based on truth tables, when see || (or operator) checks conditions truth table of or, when see && (and operator) checks conditions truth table of and. , since both or , and binary operators both of condition 'juded' 1 of them true.
or truth table
(assume , b statemnts (conditions) , r result when or on them
------------------------- | b | r ------------------------- true | true | true ------------------------- true | false | true ------------------------- false| true | true ------------------------- false| false | false ------------------------- // in or table, when both of conditions false result false // while when 1 of them true result true
and truth table
(assume , b statemnts (conditions) , r result when , on them
------------------------- | b | r ------------------------- true | true | true ------------------------- true | false | false ------------------------- false| true | false ------------------------- false| false | false ------------------------- // in , table, when both of conditions true result true // while when 1 of them false result false
i hope understand why 2 conditions must checked if 1 of them true.. example, lets have 2 conditions , b , or on them , assume false
if (a || b) // code here
in case depends in condition b, if b false code not executed, if b true code executed..
i know asked why if true still checking b condition, it's because or binary operator..
Comments
Post a Comment