my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes using comparator with array of primitives ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "using comparator with array of primitives ?" Watch "using comparator with array of primitives ?" New topic
Author

using comparator with array of primitives ?

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634


why Comparator cannot be used to sort a primitive array ?

why Comparators cannot be used when searching arrays of primitives ?


OCPJP 6.0 93%
OCPJWCD 5.0 98%
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

Primitives cannot be compared with a Comparator since the comparison is between typed objects. Primitives are not objects


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Did you try to see what happens ?


[My Blog]
All roads lead to JavaRanch
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

mohitkumar gupta wrote:
why Comparator cannot be used to sort a primitive array ?

why Comparators cannot be used when searching arrays of primitives ?



primitive type inbuild have the compare method implemented.............
so there is no need to do that


SCJP6.0,My blog Ranchers from Delhi
Deepak Bala
Bartender

Joined: Feb 24, 2006
Posts: 6661
    
    5

Primitives do not have methods
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Deepak Bala wrote:Primitives do not have methods





yes....deepak you are right..............sorry guys................
the fact is that why primitives doesnot required comparator is.............
because Array.sort() method is overloaded millions times to provide a couple of methods to sort the primitives.............

so there is no need to sort() primitives and if you are trying to do that you will get exception...(i am not sure which error may be compile time or runtime......but most probably you will get runtime exception because sort is done at runtime.)


above explaination which i give is for string class................it implements comparable interface so there is no need to sort it.......
it automatically do that in increasing order.............
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: using comparator with array of primitives ?
 
Similar Threads
Why Collections.sort is using merge sort insteadof quicksort?
search
Arrays : Help Needed
binarySearch() : Help Needed
Reverse sort of array