Java Comparable vs Comparator - Which is Best?

แชร์
ฝัง
  • เผยแพร่เมื่อ 3 ม.ค. 2025

ความคิดเห็น •

  • @PrevalentAA
    @PrevalentAA 4 ปีที่แล้ว +1

    This is the best explanation of these 2 interfaces I've seen so far. I'll recommend it to anyone I know struggling with the sorting concept

  • @khalidm5939
    @khalidm5939 8 ปีที่แล้ว +1

    You are a legend man! Definitely have some of the best tutorials on TH-cam, stay blessed!

  • @SachinVerma-xo4fj
    @SachinVerma-xo4fj 11 ปีที่แล้ว +1

    all i wanted to know was in between 26:00 to 27:55(about comparator only) still watched full video...
    you are an artist man!!! (LEVEL-VETERAN).
    thanks

  • @danielzagorsky3197
    @danielzagorsky3197 7 ปีที่แล้ว +1

    Great explanation. Everything is simple and clear. Much better than UNIVERSITY lessons i have been to. Keep up the good work!

  • @miguelehm8570
    @miguelehm8570 8 ปีที่แล้ว +7

    "It goes back to being happy!" That's exactly how I feel about compilers too ahahahah

  • @Jester8890
    @Jester8890 4 ปีที่แล้ว

    Useful video, was taking a course where this was discussed but was very vague, this helped fill in any of the gaps, thank you!

  • @johnjackson4082
    @johnjackson4082 8 ปีที่แล้ว

    I went through too many resources that couldn't explain to me that all comparable does is return a positive, 0, or negative number based on the current instantiated object and the object passed in its parameters. They just go ahead and start using it. Thank you for understanding how to TEACH.

    • @CodersCampus
      @CodersCampus  8 ปีที่แล้ว +1

      +John Jackson My pleasure... it frustrates me to no end when people don't explain the simple things sometimes... especially something as fundamental as the positive / 0 / negative thing with "compareTo"

  • @chandradharmaraj520
    @chandradharmaraj520 9 ปีที่แล้ว

    A nice explanation for which am searching for a long time. Very good effort taken in letting others understand. Thank you so much, and it helped me a lot.

  • @kevinbenavides92
    @kevinbenavides92 7 ปีที่แล้ว +2

    Great explanation thank you. Using the debug tool to emphasize what's actually happening during runtime helped a lot too.

  • @maddzkz
    @maddzkz 7 ปีที่แล้ว

    Fantastic explanation, I've been trying to figure this out for a while and I instantly got it when I saw your video! Thank you!

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      Madalena Pavão boo yah!

  • @durgaprasadnagarkatte6470
    @durgaprasadnagarkatte6470 4 ปีที่แล้ว

    A very nicely explained video. Helped me to understand the concept better.

  • @madhurchaurasia1937
    @madhurchaurasia1937 8 ปีที่แล้ว

    superb .......finally after reading many blog and videos .I found this one as a best which clarify behind story of comparable interface

  • @kokoloism
    @kokoloism 4 ปีที่แล้ว

    It is great to watch pre-lambda Comparator implementation

  • @anushakumar1332
    @anushakumar1332 8 ปีที่แล้ว

    Best video for comparable and comparator interface ! Thanks for putting the concepts clear

  • @MBadAtGuitar
    @MBadAtGuitar 8 ปีที่แล้ว

    Exceptional and brilliant teaching style..Thank you is just a word to show my gratitude to you sir..A big hug from India :)

  • @GalliadII
    @GalliadII 3 ปีที่แล้ว

    I love this video! You explain really well. Please continue making videos.

  • @kundanatre3174
    @kundanatre3174 11 ปีที่แล้ว

    Superb explanation. HATS OFF

  • @jmonger2007
    @jmonger2007 7 ปีที่แล้ว +3

    Great Explanation. I appreciate the debugging details.

  • @jayjaythomson198903
    @jayjaythomson198903 8 ปีที่แล้ว +1

    How does the Comparators's compare method know that veriables o1 and o2 are referring to the list's values in spot 0 and 1????

  • @gayatriyadav4368
    @gayatriyadav4368 7 ปีที่แล้ว

    Nice example given to explain logic... Keep it up

  • @liquicitizentimmehy1027
    @liquicitizentimmehy1027 8 ปีที่แล้ว

    You sir saved my exam!Thank you!

  • @Zharkan16
    @Zharkan16 11 ปีที่แล้ว

    return "this" - but i have many objects of that class? which object is it comparing against??? And when I run collections(sort)(however its spelled) what is my input object that I compare with? :()

    • @trevor-page
      @trevor-page 11 ปีที่แล้ว

      When you run Collections.sort(), it will compare each object IN that collection against each other object IN that same collection. For you to best understand what it means by "return this", just put a breakpoint in the compare code and you'll see how it iterates through each object in the collection and runs its compare.
      Give it a shot and if you're still unsure of what's going on, just post another comment and I'd be happy to help you out :)

  • @MamadouDIALLO-kd2xx
    @MamadouDIALLO-kd2xx 8 ปีที่แล้ว

    i don't understand English but I very understanded your tuto,thank you
    Vous êtes le maître de JAVA

  • @winstonmisha
    @winstonmisha 8 ปีที่แล้ว

    Man that was great, you are very good at explaining!

  • @sweatheart786
    @sweatheart786 6 ปีที่แล้ว

    We can use compareToIgnoreCase in class that implements comparable. Can you explain any other usecase of comparator.

  • @joe624p
    @joe624p 8 ปีที่แล้ว

    I love you! I finally know (the missing part) how to sort my LinkedList thank you!

  • @Anonymous-sm5qd
    @Anonymous-sm5qd 9 ปีที่แล้ว

    Awesome explanation..

  • @peijieliu1924
    @peijieliu1924 10 ปีที่แล้ว

    Really helpful! Awesome explanation

  • @chinmayswaroopsaini7890
    @chinmayswaroopsaini7890 7 ปีที่แล้ว

    Beautifully explained

  • @thevijayraj34
    @thevijayraj34 10 ปีที่แล้ว +1

    A perfect comparison.. what i actually wanted.. Thank you sir :-)

  • @NarendraKolink
    @NarendraKolink 8 ปีที่แล้ว

    Very well explained..!!

  • @rameshpitla783
    @rameshpitla783 10 ปีที่แล้ว

    Nice explanation and it is very helpful. Thank you for uploading these videos

  • @diksha5746
    @diksha5746 7 ปีที่แล้ว

    Can you please explain to me what this.username is? I am not sure I got that part. user.getUsername is referring to the username being passed that is tpage or zpage, right? Because user.setUsername("tpage") or user2.setUsername("zpage") was what was passed, but what about this.username?

    • @babbychugh
      @babbychugh 7 ปีที่แล้ว

      go to time 16:30 in the video you will get your answer

  • @tango8011
    @tango8011 8 ปีที่แล้ว

    I have an assignment due and it asks me to create a subclass of the ArrayList which is obviously a superclass. I have started creating it but have become stuck on how to implement the compareTo method...I am not 100% sure if this SortedArrayList class (which has to sort out the elements in ascending order) should have been done within the user class, or on its own. If it is on its own, how would I go about setting the compareTo method?

  • @poojamalik7022
    @poojamalik7022 9 ปีที่แล้ว

    This is really very helpful & good explanation of this. Thanks you so much.

  • @feligoros
    @feligoros 7 ปีที่แล้ว

    Really clear. Thanks for sharing the knowledge!

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      Thank YOU for the feedback, glad the video was helpful

  • @rushabhpatel007
    @rushabhpatel007 7 ปีที่แล้ว

    Which IDE are you using ?

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      I'm using the Spring Tool Suite, you can download it here: spring.io/tools

    • @rushabhpatel007
      @rushabhpatel007 7 ปีที่แล้ว

      Thank You!

  • @TELUGUABBAYITAMILPONNU
    @TELUGUABBAYITAMILPONNU 9 ปีที่แล้ว +1

    Nice Video, However I have a doubt:1. Before sort the list has @list(0) = zpage and @list(1)= tpage.2. While compareTo method executing its returning the -ve value3. After execution we have list like @list(0) = tpage and @list(1) = zpage Doubt is if it returns the negative value it should not switch the objects, (as you told in video) however object are switching in list. Could you please explain this. I am trying to understand your statement on this.

    • @TELUGUABBAYITAMILPONNU
      @TELUGUABBAYITAMILPONNU 9 ปีที่แล้ว

      Thanks you now I am good :)

    • @rodomod
      @rodomod 8 ปีที่แล้ว +1

      Thank you User(John bogdashkin) !!!!///@\\\!!!!

    • @SonalGupta25
      @SonalGupta25 6 ปีที่แล้ว

      Could you please explain this even I have same doubt? How the objects are getting switched since it returns -ve value?

  • @cseijifja
    @cseijifja 9 ปีที่แล้ว

    Please,if you want to sort a list of citities, but the catch is you want to sort them in base to an atribute in they have called "longitude of the city"(it's and int), how would you make it so you can compare it by a determined atribute of an object?

    • @CodersCampus
      @CodersCampus  9 ปีที่แล้ว +2

      +seiji fujii When you implement Comparable, you should pass in the object you wish to compare. This then allows you to compare based on properties of that object
      So for example:
      public class City implements Comparable
      {
      private double longitude;
      // getters and setters
      public int compareTo (City city)
      {
      return this.longitude.compareTo(city.longitude);
      }
      }

    • @cseijifja
      @cseijifja 9 ปีที่แล้ว

      thanks!

  • @whatsupbebexxx
    @whatsupbebexxx 10 ปีที่แล้ว

    Great explanation. Could you please explain this "Comparable cannot sort objects on different attributes, while Comparator can" ? bcz I believe I have implemented comparable where I can sort based on different attributes. thanks

  • @anantrao07
    @anantrao07 9 ปีที่แล้ว

    What if you are comparing float instead of string in compareTo method

    • @ryanvelazquez9263
      @ryanvelazquez9263 9 ปีที่แล้ว

      +anant rao All classes that are sub of java.lang all wrapper classes have a compare method already for example in double.
      return Double.valueOf(this.cost).compareTo(Double.valueOf(temp.cost));

  • @ynvbalu
    @ynvbalu 11 ปีที่แล้ว

    very good explanation, make the video clear.

  • @Tpmbyrne
    @Tpmbyrne 5 ปีที่แล้ว

    absolutely amazing video, exactly my style of learning. thank you very much

  • @gauravpant8093
    @gauravpant8093 8 ปีที่แล้ว

    Good tutorial.
    I have a doubt.
    For Comparator you have used compareToIgnoreCase method to customize sorting (Z and t).
    Isn't same can be used inside compareTo method by extending Comparable class to achieve customized sorting.
    i.e inside compareTo method also I can use compareToIgnoreCase to customize sorting.
    I didn't get the exact difference between Comparable and Comparator.

    • @vinod187118
      @vinod187118 8 ปีที่แล้ว

      You can do that if you are dealing with customised class which is implementing Comparable interface. But for a list of strings, you have to use comparator inorder to define ur own sorting as String is a final class. Sting class cant be extended and it implements Comparable interface. So in its compareto(), the sorting method is already defined which doesnt consider "IgnoreCase" scenario as explained. Inorder to modify the sorting method to include "ignoreCase". we use Comparator..
      Hope its clear now.. :)

  • @sujithsurendran7686
    @sujithsurendran7686 8 ปีที่แล้ว

    brilliant, at last understood concept. Thank you.

  • @srividhyasadine
    @srividhyasadine 11 ปีที่แล้ว

    nice explanation and it is very helpful. Thank you for uploading

  • @gamingbutnotreally6077
    @gamingbutnotreally6077 6 ปีที่แล้ว

    You explained it really clearly thanks!

  • @johanandersson178
    @johanandersson178 9 ปีที่แล้ว +14

    You're the man

  • @babbychugh
    @babbychugh 7 ปีที่แล้ว

    thank u... i get to know what this and the user object actually refer to? also suggest me --
    when i hover over this and user object in the statement return this.username.compareTo(user.getUsername()) in class users, my eclipse is not suggesting me which this object is referring to. please suggest me how do i get these suggestions from eclipse.

  • @ayushirautela6965
    @ayushirautela6965 5 ปีที่แล้ว

    Super useful. Thank you so much

  • @angelodls4982
    @angelodls4982 5 ปีที่แล้ว

    Everything makes sense now thanks !

  • @Avyukth-n3f
    @Avyukth-n3f 10 ปีที่แล้ว

    Excellent Explanation.Thanks alot

  • @lakshmitejaswi7832
    @lakshmitejaswi7832 6 ปีที่แล้ว

    how to sort based on both id,name

  • @gustavomaldonado6159
    @gustavomaldonado6159 10 ปีที่แล้ว

    Amazingly good! Trevor, I have been following your tutorials and have one recommendation. Can you call out all the neat shortcuts you use in your video? I know you do talk about them in other videos, but if you could just call them out as you are working through the exercise that would be awesome. It's really beneficial for newbies.

    • @trevor-page
      @trevor-page 10 ปีที่แล้ว

      Sure thing, I usually try to say the shortcut keys I'm using, but I guess I didn't stay true to that habit in this video. My bad!

  • @naveensharma2349
    @naveensharma2349 9 ปีที่แล้ว

    Awesome explanation and communication skills...... That's called Experience. Thanks. and what to use in eclipse in the place of "assert(list.get(0).getUsername(), is("tpage"));" to create this program...??

  • @codegate615
    @codegate615 5 ปีที่แล้ว

    OMFG, I sorted through dozens of HINDI videos to find you. Thanks.

    • @CodersCampus
      @CodersCampus  5 ปีที่แล้ว

      I feel ya. Glad you found this video :)

  • @joeycopperson
    @joeycopperson 8 ปีที่แล้ว

    that was great help in knowing the difference.. thanks :)

  • @bnfu3428
    @bnfu3428 9 ปีที่แล้ว +1

    Thank you, I finally get it now.

  • @subodhagrawal4087
    @subodhagrawal4087 9 ปีที่แล้ว

    But in comparable there is also compareToIgnoreCase() method. please tell me exact difference b/w these two.

    • @Codersstartup
      @Codersstartup 9 ปีที่แล้ว

      +subodh agrawal compareToIgnoreCase will compare two strings and ignore the case of the strings. I believe the lower letter 'a' would be sorted before upper letter 'A'. So if your sorting mechanism is NOT case sensitive (i.e. you don't want to treat 'a' any different than 'A') then you would use compareToIgnoreCase()

    • @johnjackson4082
      @johnjackson4082 8 ปีที่แล้ว

      +subodh agrawal The compareTo method for strings in JAVA uses lexicographical ordering which is a specific way to define how it decides the value of strings and can compare them by using this ordering. In the order they define upper case and lower case as two different entities much like ASCII. The ignore case simply doesn't define the difference between A or a.
      In other words instead of using compareToIgnoreCase() you could change the string to all uppercase or all lowercase and use compareTo(). But ofcourse if it's built into the language, don't do that.

  • @ScotHenderson
    @ScotHenderson 5 ปีที่แล้ว

    import org.hamcrest.CoreMatchers.*; is not being recognised .. I have www.java2s.com/Code/Jar/h/Downloadhamcrestcore13jar.htm downloaded and in my plugins folder and the buildpath is seeing it .. but it wont recognise it . and junit is imported but cant see the junit window down below .. anyone know how to fix these things?

  • @wBacz
    @wBacz 7 ปีที่แล้ว

    Why ya said it is impossible to do compareToIgnoreCase() in @Override compareTo() when it is possible?

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      When did I say that in the video?

    • @wBacz
      @wBacz 7 ปีที่แล้ว

      25:35 "...creating custom sorting method for Strings. But we can't do that with Comparable, can we? Well, not exactly."

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      I think what I'm saying here is that in order to use Comparable, that would mean we need to add "implements Comparable" to the String class... but in Java we can't modify the String class at all, it's sort of "native" code. So the next best option is to use a Comparator.

    • @wBacz
      @wBacz 7 ปีที่แล้ว

      ahaaa, OK now it is clear why ya've chose a String to the second example, not an Object. OK :)

    • @CodersCampus
      @CodersCampus  7 ปีที่แล้ว

      You got it :)

  • @David66Peterson
    @David66Peterson 5 ปีที่แล้ว

    awesome explanation, thank you!!

  • @anubhavanubhav7651
    @anubhavanubhav7651 9 ปีที่แล้ว

    java.lang.Error: Unresolved compilation problems:
    The method is(String) is undefined for the type test
    The method is(String) is undefined for the type test
    i am getting the error even after importing import the library as well

  • @fischebc
    @fischebc 10 ปีที่แล้ว

    What IDE is he using?

    • @CodersCampus
      @CodersCampus  10 ปีที่แล้ว

      Springsource Tool Suite (spring.io/tools) - it's pretty much identical to Eclipse, but it has a few neat tools that integrate well with the Spring framework

    • @fischebc
      @fischebc 10 ปีที่แล้ว

      I've been using net beans and this looks legit. It makes your set and get method for you!? That's awesome. That will save me some fat finger time. Lol

    • @ryanvelazquez9263
      @ryanvelazquez9263 9 ปีที่แล้ว +1

      +Brandon Fischer netbeans does it to. Right click->refractor->Encapsulate fields-> Then click which you want

    • @bassdewd
      @bassdewd 9 ปีที่แล้ว

      +Brandon Fischer Alt + insert lets you automatically create getters and setters too.

  • @anilmeher3985
    @anilmeher3985 9 ปีที่แล้ว

    Great Explanation.. Thank you so much.

  • @PUAMethodTV
    @PUAMethodTV 11 ปีที่แล้ว

    video is good, but please show us your full screen and not a zoomed in area. it is frustrating to follow the cursor around.

  • @anandk199
    @anandk199 6 ปีที่แล้ว

    the number returned is the difference between the index of the two strings compared actually... z-6 would be t... z-2 would be x and so on...

  • @norbi4148
    @norbi4148 6 ปีที่แล้ว +1

    Great video, kinda saved my life :D

  • @sudoaptgetgoodscrub
    @sudoaptgetgoodscrub 9 ปีที่แล้ว

    Was very helpful, thank you! Just wish the video would've been a bit shorter. More straight to the point or a marker that skips the beginning stuff and goes straight to the point. Other than that very informational and helped me to understand a lot better!!!

  • @mangaraoarepalli7176
    @mangaraoarepalli7176 11 ปีที่แล้ว

    Awesome Explanation!!!!!!!!! great!!!!!!!!

  • @ChindoEnyidah
    @ChindoEnyidah 10 ปีที่แล้ว

    Very helpful.

  • @ramonrahner9969
    @ramonrahner9969 7 ปีที่แล้ว

    Thx! Good explained!

  • @captainheretic
    @captainheretic 9 ปีที่แล้ว

    Can't instantiate Comparator (abstract class), thats what netbeans says.

  • @RatFace_MonkeyEar_FishEye
    @RatFace_MonkeyEar_FishEye 6 ปีที่แล้ว

    Thanks man! I finally understood it lol

  • @srinivasvadla2190
    @srinivasvadla2190 7 ปีที่แล้ว

    Bit confusing can you please clear it , and run it with java do not run with junit test and take more properties so that we can easily understand.

  • @muralikrish9434
    @muralikrish9434 7 ปีที่แล้ว

    Excellent!

  • @marinospantouris6270
    @marinospantouris6270 9 ปีที่แล้ว

    indeed very helpful !
    Thank you :)

  • @MrJonnis13
    @MrJonnis13 8 ปีที่แล้ว

    Very helpful

  • @chumyash92
    @chumyash92 10 ปีที่แล้ว

    thank you soooo much helped a lot

  • @RajYadav-cu2mq
    @RajYadav-cu2mq 11 ปีที่แล้ว

    Thank you

  • @tajpoovaiah8113
    @tajpoovaiah8113 7 ปีที่แล้ว

    Wow! Thank you. :)

  • @jagermeister5
    @jagermeister5 11 ปีที่แล้ว

    Thank you very much very helpful

  • @mosherabaev1336
    @mosherabaev1336 10 ปีที่แล้ว

    very detailed explanation but inside the body of the compareTo() method You duidn't to write this.username.compareTo(user.getUsername(); you could of leave out the this keyword.

  • @lokeshreddy4072
    @lokeshreddy4072 7 ปีที่แล้ว

    Nice explanations but I am completely confused ......

  • @briand55555
    @briand55555 7 ปีที่แล้ว

    Excellent. I listened to your podcast too. bum bum ba-dum ba-dum bum ba-bum bum ba-dum ba-dum bum

  • @amoulatar
    @amoulatar 10 ปีที่แล้ว +1

    thaank you

  • @orph4nsx
    @orph4nsx 4 ปีที่แล้ว

    Thanks

  • @anirudhrahul8956
    @anirudhrahul8956 8 ปีที่แล้ว

    Yo this vid was soo gud

  • @ivanpantic6701
    @ivanpantic6701 6 ปีที่แล้ว

    Excellent tutorial but uploading a code would help.

  • @mehrosenasir3966
    @mehrosenasir3966 5 ปีที่แล้ว

    subscribed!

  • @Xardas_
    @Xardas_ 3 ปีที่แล้ว

    classy

    • @CodersCampus
      @CodersCampus  3 ปีที่แล้ว

      Haha, glad you liked it!

  • @rahulsoni-lx5rb
    @rahulsoni-lx5rb 3 ปีที่แล้ว

    👍🙌🙌

  • @rodomod
    @rodomod 8 ปีที่แล้ว

    Thank you !!!!///@\\\!!!!

  • @qamarislam274
    @qamarislam274 10 ปีที่แล้ว +13

    confusing

    • @djus5
      @djus5 7 ปีที่แล้ว +1

      It is not confusing, Trevor did just great explanation,
      I even learnt how to use JUnit Test and debug from this video :)

  • @Synthaxdrache
    @Synthaxdrache 9 ปีที่แล้ว +4

    One of the worst videos by being not able to get to the straight point!
    Normal people would first explain everything and THEN make a review of possible mistakes!

  • @fredwu6812
    @fredwu6812 7 ปีที่แล้ว

    bad code! Never Users as a class name, put User. Never plural.

  • @lesbianGreen
    @lesbianGreen 11 ปีที่แล้ว

    thanks for the video, it helped me very much.

  • @anbarasannagalingam2131
    @anbarasannagalingam2131 9 ปีที่แล้ว

    indeed very helpful ! Thank you :)

  • @prajaktaupadhye1791
    @prajaktaupadhye1791 10 ปีที่แล้ว

    Thank you