Interview Question | Comparable vs Comparator in Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 29 ก.ย. 2024
  • Check out our courses:
    Spring and Microservices Weekend Live Batch : bit.ly/spring-...
    Coupon: TELUSKO10 (10% Discount)
    Master Java Spring Development : bit.ly/java-sp...
    For More Queries WhatsApp or Call on : +919008963671
    website : courses.telusk...
    Instagram : / navinreddyofficial
    Linkedin : / navinreddy20
    TELUSKO Android App : bit.ly/TeluskoApp
    Discord : / discord
    In this video we will see :
    - Comparator and Comparable in Java
    - Difference between Comparator and Comparable
    - Example of Comparator and Comparable
    - Create getters and setters
    - toString() method
    - Creating List and adding values in List
    - Collection.sort method to sort the List
    - When to use Comparable and when to use Comparator
    - compareTo() method
    - How to use comparable
    - How to use Comparator
    #java #interview
    Java and Spring Framework For beginners with Spring Boot : - bit.ly/3LDMj8D
    Java Tutorial for Beginners (2023) :- bit.ly/3yARVbN
    Editing Monitors :
    amzn.to/2RfKWgL
    amzn.to/2Q665JW
    amzn.to/2OUP21a.
    Subscribe to our other channel:
    Navin Reddy : www.youtube.co....
    Telusko Hindi :
    www.youtube.co....
    Donation:
    PayPal Id : navinreddy20
    Patreon : navinreddy20
    www.telusko.com...

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

  • @raragam
    @raragam 4 ปีที่แล้ว +61

    This guy is simply amazing. Hats off to his teaching abilities !!

  • @Evilshrimp02
    @Evilshrimp02 4 ปีที่แล้ว +2

    This guy is the man. Thanks a lot.

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

    Very nice video on just the topics you are wondering about. Teluko, tussi great ho ji!

  • @Pravin-hj2wj
    @Pravin-hj2wj 4 ปีที่แล้ว

    Your explanation is really superb. I was able to quickly grasp why these interfaces are used & where used from this video. Thanks so so so much, Navin.

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

    Perfect explanation 👍

  • @VishalThakur-zg7ub
    @VishalThakur-zg7ub 3 ปีที่แล้ว

    Yes, I enjo.. I mean understood what is comparable.

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

    Best explanation I've found, thanks

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

    Thank you. Very informative video

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

    thanks a lot

  • @praneethachebolu278
    @praneethachebolu278 2 ปีที่แล้ว

    here inside the anonymous class we wrote compare() right? does it have to be compare() or can the be different like comparing() or comparePrice() or something?

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

    How does all the elements of the laps are compared when sort method. I mean how does all laptops are iterated?

  • @saby8765
    @saby8765 6 ปีที่แล้ว +212

    Perfect...
    1. for known datatypes like String, Int the classes have already implemented Comparable, so you don't need to bother about it.
    2. For your own Objects you need to implement Comparable to make the sort() work, which is basically mimicking the strategy for point 1.
    3. If you want to change your sort logic implemented by your Comparable interface you need to use Comparator, for either known datatypes or your own classes.
    4. You can make the sort() for your own classes work if you implment Comparator interface, whether you have implamanted Comparable or not.

    • @naksnaz
      @naksnaz 4 ปีที่แล้ว +3

      ​@@AK-rx5yp : I have on doubt when we can write our own logic with compare To() method if we are implementing Comparable why should we use Comparator interface?

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

      What is difference between comparable and comparator

    • @showdank
      @showdank 4 ปีที่แล้ว +11

      @@naksnaz using comparable you can give only one logic and its locked.. Locked meaning you have given that one logic to sort in your class which implements comparable. In this case sort by RAM.
      comparator comes handy when you have sort by multiple fields. You can use comparator to sort by BRAND and then again use that result to sort by PRICE.
      Basically to have multiple sorting. Which is not possible using comparable.

    • @altamashalisheikh
      @altamashalisheikh 3 ปีที่แล้ว +1

      @@naksnaz change default sort() work, means by default it's sorted by ram if want to sorted by other parameter need to use comprator.

    • @altamashalisheikh
      @altamashalisheikh 3 ปีที่แล้ว +5

      @@sathyalalithanjaliavadhanu835 comparable interface basically work for sort objects by default parameter bt using comparator we can sort objects according to our choice parameter.

  • @filip8467
    @filip8467 3 ปีที่แล้ว +43

    Comparator is a functional interface, so you can pass a logic directly by lambda through argumen list like that:
    Collections.sort(laps,(lap1,lap2)=>if lap1>la2 return 1 else return -1)

  • @learnshare9893
    @learnshare9893 3 ปีที่แล้ว +9

    "Do simple things, simple things are great" - This Video

  • @AnirudhSharma9211
    @AnirudhSharma9211 3 ปีที่แล้ว +16

    9:55 I just wanted to add that sorting based on Price can also be done using Comparable, if we override compareTo method to compare prices. Also, a major difference is that we can have multiple comparators in a class, but only one comparable. I experimented and tried to create a second compareTo method in my class using anonymous class, but failed because 'this' keyword wouldn't have scope inside the anonymous class. That's when I realized that compareTo actually compares the present instance of a class to the passed object, which is why there can be only one in a class. compare method has no such restrictions, and it doesn't even have to be in the same class, because it uses two distinctly defined objects.

    • @praneethachebolu278
      @praneethachebolu278 2 ปีที่แล้ว

      here inside the anonymous class we wrote compare() right? does it have to be compare() or can the be different like comparing() or comparePrice() or something?

  • @steviet5246
    @steviet5246 5 ปีที่แล้ว +20

    I'm here to learn for my exams, nobody explained it so simple like you thanks!

  • @user-bq2lb7kn2e
    @user-bq2lb7kn2e 5 ปีที่แล้ว +12

    Normally I don't leave comments on these types of video's, but I must say that this video is very helpfull.
    I have an exam due tomorrow and just wanted a quick refresh of one of the subjects.
    Thank you!

  • @zombnie
    @zombnie 5 ปีที่แล้ว +11

    i have been searching for a good source of comparison between these two for days. Finally one video which explains the difference perfectly.
    Thank you so much Navin

  • @AshishBurnwal
    @AshishBurnwal 6 ปีที่แล้ว +44

    You are awesome... You teach in such a manner that anyone can pick. Thank you so much

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

      are you crazy? this was way too fast and he didnt explain what he did via autogenerate. thats not good teaching imho.

    • @mrp12-ii
      @mrp12-ii 4 ปีที่แล้ว

      @@habdochkeineahnung his older videos explain all that. The title says interview questions where he assumes you already know the basics and are preparing for the interview.

  • @hasmi_intentart
    @hasmi_intentart 5 ปีที่แล้ว +15

    Clearly explained, this is wt exactly I was expecting for😍

  • @axeedo
    @axeedo 5 ปีที่แล้ว +6

    Wow! Just wow man! You are the MVP!
    There is no other place on the internet where I could learn these concepts without getting lost. You made it look so simple. Thank you very much!!! You are very talented in teaching!

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

    By using Comparable we can sort the objects based on any data member. For example, lets say we have an Author class has data members: Author name, book name and author age, now if we want to sort the objects based on any of the data members then we can use Comparable but what if we want to have multiple sort choices and we can sort objects based on any choice, this can be done using Comparator interface, we can create as many Comparator as we want and then we can call Collections.sort on one or more Comparator

  • @health.upgradedbyscience.7309
    @health.upgradedbyscience.7309 2 ปีที่แล้ว +2

    Brilliant explanation, so important to know both approaches - i was not aware of the second one before - thanks a million!! 😆

  • @maneaniket4200
    @maneaniket4200 5 ปีที่แล้ว +4

    Nobody does the job of using code to explain concepts... Great Naveen.. Thanks For The Video..

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

    Naveen, you're just great!!
    Brilliant and hilariously easy-to-understand explanation.
    Not everyone has got the ability to teach things in a simple manner as you do..Einstein of Java I must say

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

    Collections.sort(myObservableList, (
    MyModelClassp2, MyModelClassp1) -> new Double(p1.getTotal()).compareTo(new Double(p2.getTotal()))); 🌟

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

    Collections.sort(myObservableList, (
    MyModelClassp2, MyModelClassp1) -> new Double(p1.getTotal()).compareTo(new Double(p2.getTotal()))); 🌟

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

    Collections.sort(myObservableList, (
    MyModelClassp2, MyModelClassp1) -> new Double(p1.getTotal()).compareTo(new Double(p2.getTotal()))); 🌟

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

    you dont need to use if statements on what to return like you did this > 2ndObj?1 and all this
    you can just return this.(whatever) - 2ndObj.(whatever) and it will just return you + - or 0
    no?

  • @zstar8397
    @zstar8397 ปีที่แล้ว

    Yo just wanna say that GOD loved the world so much he sent his only begotten
    son Jesus to die a brutal death for us so that we can have eternal life
    and we can all accept this amazing gift this by simply believing in him (Jesus) asking for the forgiveness of your sins
    and forming a relationship with heavenly father.

  • @dgabrielm
    @dgabrielm 6 ปีที่แล้ว +3

    Hi Navin, thanks so much for making this video. It is really clear and logical and gives you the understanding of WHY we use each one. compareTo(myUniversityProfessor) who just writes the syntax on the board and shrugs his shoulders. Brilliant!

  • @nithya6361
    @nithya6361 6 ปีที่แล้ว +3

    Hi Sir, can you explain how to do customized sorting with comparator??

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

    or you can dirctly pass this Collections.sort(laps,(l1, l2)->(l1.getRam() > l2.getRam()) ? 1 : -1);

  • @mahammadkhaja9478
    @mahammadkhaja9478 2 ปีที่แล้ว

    Hi , I saw so many of your videos which doesn't have theoretical part. To adding at least 1minute of theory at the beginning of the video I think It will be better for both freshers and professionals.

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

    Comparator custInt = (a,b) -> a>b?1:-1; will work. If it is in the same line this works.

  • @deepakshakya9597
    @deepakshakya9597 3 ปีที่แล้ว +2

    Your teaching skills are amazing!!! Thank you so much for making such valuable videos

  • @sheriffcrandy
    @sheriffcrandy 3 ปีที่แล้ว +1

    Bro I love you man haha I was so confused on the differences between comparable and comparator.

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

    I have question
    We can get list of laptop from DB based on price, name etc . So where we should use comparable or comparator little confusion

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

    I have on doubt when we can write our own logic with compare To() method if we are implementing Comparable why should we use Comparator interface?

  • @shivaramkrishnadurgi4253
    @shivaramkrishnadurgi4253 2 ปีที่แล้ว +1

    Mr. Perfect @Navin Reddy... Loved your teaching style...Awesome!!!

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

    when i am executing both these codes in my eclipse i am having error in second code runner at point of adding objects...laps.add??

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

    Where does compareTo() method getting call? Is it somewhere hidden while calling Collections.sort() method ?

  • @sarathykrish3212
    @sarathykrish3212 2 ปีที่แล้ว

    You want to use comparator when
    1) you want to implement your own logic
    2) if you don't want comparable interface

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

    can anyone tell me the font which he is using in this eclipse ide? By default, it is "Consolas" in my ide. I'm sure this font is not "consolas".

  • @Varun-ij2pp
    @Varun-ij2pp 2 ปีที่แล้ว

    If Comparable and comparator both are defined while sorting which will be used? compareTo or compare

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

    Thnaks a lot but I still have a struggle understanding when and why to use Comparator and Comparable.

  • @HimanshuSingh-es4qq
    @HimanshuSingh-es4qq 4 ปีที่แล้ว

    Nice but you made this in 2018 still not used any java 8 features !! step up ur game :)

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

    Why to use comparable when comparator can be used for all the cases, Is there any case where we only comparable can be used. or why we need to use comparable instead of comparator.

  • @programmingforfun4158
    @programmingforfun4158 2 ปีที่แล้ว

    His explanation is so easy that you are bound to learn. If you can't learn from him, then coding is not for u

  • @tejasjani2544
    @tejasjani2544 2 ปีที่แล้ว

    Without interface we can simply asd new method for comparison. it's also work.

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

    But which is the second object and how it picks the second object if there are number of objects in the list?
    How it select which object is to be compared with this object?

  • @kavansingh-k3q
    @kavansingh-k3q ปีที่แล้ว

    Thank you so much sir, this was the easiest explanation I could fine online.

  • @nasamind
    @nasamind 5 ปีที่แล้ว +1

    Nice.. your explanation is very simple.. I went through other explanations but yours is easy to understand..

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

    Why can't we use (a,b)-> return a.price- b.price; inside sort

  • @sanketkamble8415
    @sanketkamble8415 2 ปีที่แล้ว

    bro ... please make future videos in large fonts ...its not visible on mobile... its humble req

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

    Thanks pal , very useful video. Greetings from Colombia.

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

    laptop object is not belong to integer or String class so at that can we use our own logic using comparable interface

  • @jatinderarora2261
    @jatinderarora2261 5 ปีที่แล้ว +2

    Awesome. Thanks for sharing your excellent knowledge !

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

    return this.getRam() - lap2.getRam(); //much shorter

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

    Excellent explanation.Thanks :) I am new subsscriber

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

    Hi Navin, what if price will null then which value should return?

  • @MsEtatDame
    @MsEtatDame 2 ปีที่แล้ว

    How is that possible that we can do something like "new Comparator ()" which is a interface ?? Interface cannot be instanciated right?

    • @Ashu_Kumar21
      @Ashu_Kumar21 2 ปีที่แล้ว

      It's not direct object creation but rather implementation object of Comparator Interface

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

    I know you are very smart, but you can speak slower... a bit...

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

    sir great .....i m java developer.....your teach way is too good(tussi kmaal krde hunde aa)

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

    And for those who still don't know, what Telusko did for the code of the compareTo() method.
    This code here is the equivalent and much shorter to type:
    @Override
    public int compareTo(Laptop lap2)
    {
    return Integer.compare(this.ram, Laptop.ram);
    }

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

    You saved my midterm! Thank you sir!

  • @thomachanrj9064
    @thomachanrj9064 6 ปีที่แล้ว +12

    Collections.sort(laps);
    laps.forEach(System.out::println);

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

    thank you sir, this video was crystal clear for me

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

    why you calling other humans ALIENS?

  • @SaiSSOfficial
    @SaiSSOfficial 2 ปีที่แล้ว

    Hello Dear, can you please explain about the first object again in a simple way, lots of confusion is there.

    • @SaiSSOfficial
      @SaiSSOfficial 2 ปีที่แล้ว

      Are you there Navin ji....or anybody can you please tell me about 1st object in compareTo().

  • @karthick2237
    @karthick2237 5 ปีที่แล้ว +3

    Oh we have to mention explicitly, 👍

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

    Thank you, your video on comparator and comparable made the concept so easy to understand. Simple and straightforward, thanks once again.

  • @saikumarnarani8173
    @saikumarnarani8173 2 ปีที่แล้ว

    Simply Amazing..!!! Thank you so much

  • @RahulSharma-yr7mi
    @RahulSharma-yr7mi 2 ปีที่แล้ว

    Mashallah, explained very well, hats off sir😊

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

    10:25 Can someone explain why we are creating an object using an interface. I might have missed his point when he was explaining it.
    Great video btw!

  • @alejandropenna3094
    @alejandropenna3094 10 หลายเดือนก่อน

    Amazing man, the best explanation by far

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

    More CS professors should watch your videos to learn how to explain these concepts better. Thank you so much!

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

    Amazingly clear explanation. Impossible not to get it !!! I rarely subscribe to anyone, but for this time LIKE and SUBSCRIBE just to thank you for this video! :)

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

    Great explanation!!! but I have this little doubt regarding the implementation of the compare method inside the Comparator anonymous class.
    here in method, compare(Laptop L1, Laptop L2){}
    both are the instances of the class Laptop. so how is it referring to the index(0) and the index(next) element without even assigning them with their respective element to compare?
    In short, how does it figure out which element's price it should return when you type (L1.getPrice similarly to the L2.getPrice).

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

    Were is HP laptop?
    GRRRRRRRRR!!!!!!!!! -_-
    Jokes apart, beautiful video to watch Telusko Learnings. Thank you

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

    If I want to sort in descending order, then should I just change the values being returned?
    for example - if(this.ram > laptop2.ram){return -1};
    is it correct?

  • @Hufsa
    @Hufsa 2 ปีที่แล้ว

    First time here and I totally understand why you have 1.57 M subs, you are a real master! awesome explanation.

  • @alvinchipmunk7279
    @alvinchipmunk7279 2 ปีที่แล้ว

    In the second case it’s better to use lambda expression than anonymous class, cause Comparator is the functional interface. Thanks for video

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

    sir, is compareTo() automatically called like toString() ?

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

      Same doubt...
      If you know now then help me

  • @kbhardwaj1989
    @kbhardwaj1989 5 ปีที่แล้ว +1

    You explanation are always superb. Thanks you.

  • @ektagoyal3172
    @ektagoyal3172 2 ปีที่แล้ว

    Best tutorial that made so complex logic seem so simple

  • @adnanmerrakchi3301
    @adnanmerrakchi3301 ปีที่แล้ว

    nice tutorial thank you so much, i have a small stupid question why if the class of 3rd library doesnt implement a comparator, we cant change the class file and make the class implement the comparator interface ?

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

    Similarly how can I sort the Strings.?

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

    please explain functioning of sort method and
    how it works with return values 1 ,-1, 0?

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

    If you want more detailed explanation go for Durga sir videos, this guy is awesome but he is missing clarity

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

    What is lap2 mentioned here? Which it will refer

  • @krishjlk
    @krishjlk ปีที่แล้ว

    For Final and Abstracr classes we can use Comparator becoz we cannot make them comparable .. Wonderful Explanation

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

    Ur way of teaching is very lucid and impressive too. Please make some videos on java 8 and 9.

  • @AhmedVlogs1
    @AhmedVlogs1 6 ปีที่แล้ว +4

    You made the concept so easy to understand.thank u sir

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

    you are awesome! completely understood the concepts. before thins wherever I was reading about comparable and comparator, I was getting more confused.

  • @pankajmalvi6761
    @pankajmalvi6761 5 ปีที่แล้ว +2

    finally "THIS" ka doubt solve hua ,,, i knew this but just cant clicked :-D

  • @fearless-trader
    @fearless-trader 5 ปีที่แล้ว

    Can we specify multiple conditions in comparator logic while sorting list , just like we use multiple where clause in SQL query.

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

    Hi Naveen You are simply AWSOME :-) just one thing I would suggest you plz provide a gitHub link for all codes so we can easily play with that Thank you

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

    The way you explains is too good. I am learning from last 7-8 years but I didn't get this type of explanation any where else. 👍👍

  • @ArquimedesOfficial
    @ArquimedesOfficial 3 ปีที่แล้ว +1

    Amazing tutorial man, thanks.