java - Error When Comparing Objects of Type Double? -


this question comes after piece of code (an implementation of binary search). appreciate if tell me why not outputting expected answer:

public static void main(string[] args){     double[] array = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0};     binarysearch s = new binarysearch(array);     system.out.println(s.searchnexthighest(2.0)); }  public binarysearch(double[] array){     numbers = array; }  public integer searchnexthighest(double y){     return binarysearchnexthighest(0, numbers.length-1, y, numbers); }  public integer binarysearchnexthighest(int min, int max, double target, double[] array){     int mid = (min+max)/2;      if(target==array[mid]){ //fails here         return mid;     }      if(max<min){         if(min>=array.length) return null;         return mid;     }      if(target>array[mid]){         return binarysearchnexthighest(mid+1, max, target, array);     }else{         return binarysearchnexthighest(min, mid-1, target, array);     } } 

output: 1

i followed through debugger , made absolute sure. @ moment, target = 2.0, , mid=2, , array[mid] = 2.0. yet if statement not execute.

curiously, error not occur when integer arrays/targets used.

what happening here? thougt these things happened when comparing big numbers. other pitfalls exist?

[edit] here simplified version:

public static void main(string[] args){     double[] array = {2.0};     double target = 2.0;     if(array[0] == target) system.out.println("yay!"); } 

output: none

[edit2]

public static void main(string[] args){     double[] array = {3.0};     double target = 3.0;     if(array[0] == target) system.out.println("yay!"); } 

output: yay!

someone in comments pointed out error result of comparing objects. why isn't automatically unpacking?

[edit3] here code using integer object:

public static void main(string[] args){     integer[] array = {3};     integer target = 3;     if(array[0] == target) system.out.println("yay!"); } 

output: yay!

so guess reason obvious, why object integer implemented differently? automatically unpacks itself.

double , double 2 different things. double creates object , equal if pointing same address in memory. values holding can same, different objects, not equal. same integer. code can use double instead or compare through .doublevalue() or .equals() method double compare values.

edit: pointed out @markpeters , @tedhopp in comments, integer behaves bit differently, more info here.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -