shubhch32's blog

By shubhch32, history, 7 years ago, In English

I needed to sort elements for which I used Arrays.sort() function. I read somewhere that it sorts in O(nlogn) time only for arrays containing objects as elements (Integer, Double, etc. but not int, double). But when I was comparing elements in the array after sorting, it showed some weird behaviour. Comparing elements upto 127, it compares correctly but after that it gives wrong results. Any reason as to why?

Here is my code where seq[] is an Integer array (and not int seq[]):

if(seq[i]!=seq[i-1]) map.put(seq[i],count++);

  • Vote: I like it
  • -23
  • Vote: I do not like it

»
7 years ago, hide # |
 
Vote: I like it +9 Vote: I do not like it

Do you know the difference between == and equals()?

Integers in range [-128, 127] are created in advance and are taken from cache, while other Integer objects are created newly every time.

  • »
    »
    7 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Oh ok. Thanks. Yes I know the difference between the two but I tend to use equals() only with strings. That's why didn't notice that. Thanks a lot for pointing out :)

»
7 years ago, hide # |
 
Vote: I like it +7 Vote: I do not like it

For Integer comparisons, use the method intValue()