Java collections interview questions | Why HashMap Keys are Immutable? | Immutability & HashMap

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey there everyone welcome back my name is avilash and you are watching selenium express and in this episode we are going to talk about another interview questions on immutable objects right so in the last session i have given you kind of a walk through what is an immutable object how to create it what are different catches with immutable objects and you know how to protect or how to prevent our immune immutable objects from different different scenario but i also left you guys in that particular episode with some questions and those are more like some advanced questions and i'm sure that you will be facing them in your interviews so it's better to be get prepared with that so the first question your interviewer might counter you whenever you guys have a discussion with immutable objects and someone might might counter you with the questions okay so when you create objects when we create hashmap or when we create hashmap objects or map objects the map declaration how basically declare a map we just do hash map key value then map is equal to new map so if you talk about the keys of the uh keys of the hash map they are always immutable objects okay uh it's a key you you use string you use integer as a key you use double as a key maybe in a float is a key so double floored integer these are the wrapper classes and the wrapper classes are immutable you use string as a key in the hash map so string is always immutable okay string is also immutable in java so why why the hashmap keys are immutable is it mandatory that okay the keys must be immutable or can we use mutable objects in the hashmap key okay let's say i'm declaring a hashmap can i use a mutable object as a key in the hashmap right questions right argument isn't it so yeah so when someone counters you with this kind of questions how we should deal with that so before i uh get into that thing i will do one thing let me share my screen of course i'm sharing okay so this interview questions here only i think i remember we have uh created an immutable class which is student class in the last session and i told you that this student class is immutable you can see all the fields that we have are final there are no setters available only the getters are available and also we have uh we have made sure that this particular class is final so that no other classes can extend to our student class so immutable class should be final just like the one we have created here for example if you go to string if i hit command shift t and if i'm gonna go for the string object coming from java.lang you can see there is a f uh mark here uh that stands for that this particular class is final if you open up this class so you can see your string class is final just like you know if you open up any wrapper classes just like integer okay you can see coming from java.lang integer class that's marked as final so all the wrapper classes just like integer which is final if you'll open up the double uh go for the double one which is coming from java.lang you can see a f mark here that stands for final so um i mean whatever the classes we basically used as a key in the hashmap they are final and also the one class that we have created in our last session our own custom immutable class that is also we have made it final now the question is if i'm gonna remove this final from here okay let's say right now i'm creating a class i'm not giving any setter for this variable because all these variables are final and i don't have any setters right now how do you think if i'm not writing final here or if i'm not declaring my class as final then how it can impact your hashmap performance right or how you can how it can impact your overall programming in java valid questions well lot of questions a lot of questions but let me give you the solution for that let me start you know coding something so which is going to make more sense to you so now let me reboot it back to the previous state let me close all the files that i have opened and let me start you know giving you some new examples on immutable objects this is gonna make more sense to you okay so first of all let me close this particular project and i have created another project called interview question immutable part two i'll go to the source and i got a you know package created here called com.seleniumexpress.demo and i got app.java this particular file which is empty and let me start writing code and right now first let me tell you that what will happen if i will use a mutable objects as a key in the hashmap and before you go for this make sure you understand how the hashmap works internally at least the basics uh how the how basically the hashmap works internally very popular interview questions before you go forward with this particular video make sure at least you have a little bit of understanding with that and if you don't then i also got some videos a few years back i have created a few videos like you know how the husma basically works internally i'll give you the link in the description and also in the i button above go and check there okay so now let me get started with this particular you know episode yeah let's go for that all right so first of all let me start declaring a map here let me say a hash map and the key first i'm going to take a string the value let's say as a string as well and let's say a map is equal to new hash map okay i'm creating a hashmap object here and let me collapse this and i can simply say a map dot put and i can say obvious as key which is a string and the value is also going to be a string let's say you know some value let's say the country india okay i'm putting a value in the map and if i want to get it obviously i'll do a lookup operation using the get i can do that map dot get and i'm going to say uh avilash here okay which is going to give me the value back for the key of elash in that case it's going to be india so if i'm going to run this application uh it should be you know india printed on my console pretty simple nothing to explain here right now the question is this string is immutable right now instead of using string which is a predefined class i want to create one of my own class and i want to use that as a key for an example if i'll go back to here let's say i want to create one of my own class let's say student class and this student class does have one variable private string name and let's say i'll have getter and setter for this name getter and setter which is going to be a mutable class it's not immutable it's a mutable class and also i'm going to create a constructor and i will make sure to initialize this name so string name i'll pass it in the constructor parameter and this dot name is equal to name cool so i got a student class created here okay and i'm gonna use this class as a key in the hashmap so i'll come here instead of string right now i want to take the key as student okay so right now the put method is going to complain because it's going to take student as a key so let me create an object for student let me make it full screen so i'll be creating a object for students i'll be writing student student or is equal to new student and here i'm gonna give avilash as a uh you know data right now this obvious that i'm giving here if you'll go to the student class now uh the villas will be get captured here then this dot name this name will be avilash right right now this name is initialized with a village right cool so right now if i'll go to app.java i i am i'm done with creating an object now i'll be using this student object as a key in the hashmap okay so i'm gonna paste the sorry i'm gonna paste this student object that i have created right here inside map.put method so there you go right so now it's now it looks good right map okay why i'm giving code not needed basically this student object i can directly put it here inside the put method okay fine so now here what i'm trying to do i am trying to create a hash map using the key value pair the key is the student object which is the custom object i'm using that as a key and if you have understood hashmap well you might have understood that whenever we're using any custom objects as the key in the hashmap we have to overwrite the hashcode and equals method so i'll go to the student class and i'll make sure here i'll be overriding the hashcode and equals method because that is a contract and i assume that you understand it and if you don't please go back to my previous videos on hashmap and please do check that right there so i'll go to source and i'll generate the hashcode and equals here through my id so my hashcode and equals got generated and i'll go to app.java right now happily i can use my student object as the key in the hashmap so i can do map.put student and india just right here right now if i'll be doing map.get and if i want to get the key uh the value for the key called student i'll just write map.getup student if i run this i'll get india as an output right uh cool because this is the student object that i'm using as a key and the value for that key is india so whenever i'm saying map dot get of student obviously is giving me india back perfect everything is very smooth so far okay cool now what is the problem right we are using our key which is our custom class called student uh as a key in the hashmap then there is not no problem right it's working is behaving fine right here so uh maybe maybe i can create one more object here like student student 2 is equal to new student and i'm gonna initialize this student as frank and basically i can do what map dot put and i'm gonna put the student object as a key my student object is this student to copy this paste it just right here and the value i can give anything let me say give let me give the value as us and i can just simply do copy and paste it again and right here instead of student i want to get the value of the key student to copy this and paste it just right here ctrl s run the particular program and it's going to give me us as the value because for the student 2 as a key uh the value for this key is us obviously so that's the value i'm getting no problem so far but here is the problem first of all let me remove few things so this student too and everything is just to show you let me delete this piece of code and also let me delete the line number 18 here okay so only four lines of code that i have here okay so right now what i'm gonna do let's say uh i'm trying to put my key value pair just right here in the line number 14 and once i do put it right here in the line number 14 i'm gonna do something the student object that i have created in the line number 12 i'm gonna do student dot set name and i'm gonna change the name change the name of this particular student so previously the student name was avilash now let me change the name to let's say something else let me say it's gonna be changed to frank now here you see what is the problem we'll have if i'm gonna run this particular program right now so you see in the line number 19 i'm doing map.gate so i'm trying to get the student class object this student this student i'm putting just right here and i'm giving the value as india so whenever i'm going to get the value for this student as a key obviously i should get you know india as an output but you see what we are going to get run this and there you go no your hashmap functionality just got broken i am not able to look off for a value by using a key i'm just doing map.getup student what i expect here here only i have entered the student object to my map and the value was india for that particular key but whenever i'm looking for the value for the key call student i'm getting null as an output where i should get india as an output right so what's the problem so the problem is here is the mutable object right right now our hash map key is student which is basically a mutable object so edge is a mutable object is property is getting changed right edges properties is uh is getting changed or its properties are getting changed so this particular student state if this particular object state is changing okay and that's basically impacting our hashmap performance right now you must you must be asking me how it is impacting okay how changing the property you just did the you just updated the student name of the last two prank then how did it's impacted the hashmap that's because i'm gonna tell you something okay so basically whenever right now let me comment this line number 17 control s run this application and you will be seeing that you are getting india as an output which is which is perfect so basically the how the hash map works whenever you try to put something in inside the map table what basically happens uh the hash code get calculated then we prompt that hash code the index gets calculated and your object uh the key value pair that you are trying to store which is student in india that will be stored inside a hashmap bucket or inside a are a bucket right so inside the map table where basically the data is getting stored whenever we are doing a map.get we have to basically look for the data inside the same bucket right i'm gonna give you an example right now it's gonna make so much sense to you so basically i'm gonna give a break point in the line number 14. i'm gonna give you another break point in the line number 19 and let me have another sis out here which is gonna do nothing i just want to give one more break point here on the line number 21 okay just want to show you when we are basically putting something inside the map or we are trying to look up something inside the map what is basically happening let me start this particular program in debug mode so i'm gonna debug my application is uh i mean debug my uh code so you are going to see something right here now you see we are trying to put something inside the map uh where is our map object my map object is here um so if i'm gonna open this up my map object is obviously entry let me click this so you can see the table the map table is right now null now whenever i will be putting the first element inside my map obviously my map table will be initialized and obviously 16 number of buckets will be created so if i will be do a step over okay you can see right now my map more count has been increased that's because we have inserted one element to my map so if i if i'll be you know expanding my map table you are going to see here in the bucket number 10 we got a node we got a object which object that object that we try to insert student is my object and basically india is the value is the key is the value so if you you know expand this we should be having our key which is student and the value is india so if you're gonna open this student then obviously the name we have initialized with avilash so basically right now the the the i mean the main point here whenever we're trying to insert something to our map the hashcode is getting calculated okay the hashcode is getting calculated for this object called student and then from that hashcode the index is getting calculated and right now the index which is getting calculated is 10 so inside the 10th bucket what is basically happening our object is right now there student object and the value is attached to this is india so in the next line whenever i'll be doing map.getup student now our program will do what our hashmap will do what okay so you want to get the student object again so let's do a hash calculation again for this particular object and again you know after the hash calculation again the index calculation will be done right now it will find that okay the index is right now 10 inside where we got the object right now it will it is go and look inside the tenth number bucket and it will find our object and it will give the value for that object which is india that's why whenever you are running the line number 19 you are getting india as an output in simple what so if i'm gonna do step over you are getting india as an output right so the hass code has code is here basically coming into the picture so right now if i'll come out of this java perceptive if you are going to see uh the our custom object student here we have given our hash code implementation right now see here how our ide has created this house code method for us basically this has code method when it will be called when we will be inserting a data into the map this hashcode method will be called okay because the index calculation need to be done right where basically we are going to place an object how we will be knowing it by using the hash code right basically this has code method will be will be called so right now what you can do you can just give a breakpoint here in the line number 21 now you see what is going to happen if you go to your app.java okay and if you try to debug it again debug a java application so i'll do switch okay now my plo is in line number 14. let's say right now i'm trying to insert a object to my map that's the student object so if i do step over the first thing what will happen for this student object in which bucket the object student should go for that the house code calculation will be needed and accordingly the index will be calculated and this object will be pushed to that particular index but right now how the haskell will be calculated so if i'll do a resume you will see that my flow went to the hashcode method passcode method of what has got method of my student class is my own hashcode method and how i am generating my hashcode i am generating my housecode if you see here by using this name what is this name do a control click this name is my variable the name is my property which is right now obvious it's initialized with a village right when i created this particular student class object just right here i have given a value here called velash okay so right now if i'll come back to here this name is right now initialized with obvious so right now this has code will be calculated this has code will be needed by my map to place my object inside a particular bucket so if i'm gonna do step over step over step over you can see the name.hashcode.app calculated here from this name the hashcode would have calculated just right here and obviously this result is getting returned right and this result is basically containing my hashcode which is getting returned uh to my map and my map is basically using this particular hashcode so right now if i'm gonna do a resume obviously my you know object will be inserted this particular object will be inserted to my map if you are going to see here the object inside the map map table if i'll go to the map table inside the map table right now we should have our variable which is the which is inside the 10th bucket so right now again you can see the key is student and the value is india right now whenever i'll be trying to get that particular student object again what will happen how how this uh you know get operation will work the map will again look inside your look inside your table right the your hash map uh your program should look inside this particular table and needs to find this particular student key but how it how your you know program is going to know that inside which particular look for the value right or look for that particular object and to find that again it's gonna take the help of the hashcode method so if i'm gonna do resume again when the get method will be executed the hashcode will be called now see the house code is getting called right again if i'll do step over step over now the house code will be calculated from the name itself if you remember the name was already initialized from the name the house code will be calculated just right here and that hash code will be assigned to this and if i'll do resume again what will happen right now it found the value india how it did found because it is found right inside inside this map table inside which particular bucket it need to look right right now it knows that i need to look inside the bucket number 10 here only the object student is available and the value for that is india that's what we are getting in the console whenever we are running this map dot get and then if i'll release the program the program will be terminated but here is the question here if you see the hash code right now the problem here is the house code that we are calculating we are basically calculating using these fields okay and as this particular object is not a mutable object it's a mutable objects this name can be changed so if the name will be changing then the hash code will also change right because now this has code method will give us the hashcode back but the way it is calculating the hashcode by using this name.hasscode right using this name using this name properties right so if i'll change this name to a village to uh you know something else that's a village to frank or a village to priya then obviously what will happen you know the priya has code and the villas house code will be different right so that's why the get operation was not working at that time so if you see here do control s it will go back to your app.java and right now if i if you're gonna uncomment this line number 17 okay so you will see that it will uncomment this one if i if i'm going to debug it again so first of all now whenever the map.put will be executed if i'll do resume it will go to the hashcode method it will use the hashcode to put that object inside a particular bucket right now if i'll do resume again if i'll do step over step over step over it is gonna calculate my hash code and it is going to return this particular hashcode back to my in a hashmap class then a hashmap class will do some work and it is going to insert this particular object student inside my map but whenever we are going to do get during the time i do the get it you can see using the setter method i have changed that particular state of that particular object i have changed the content of that particular object right now by using the set name if you see the name right now the name is right now changed to you know uh frank right now what i did here the name i changed it to prank if you see this is the value if i'll go to my student class right now this village is changed to frank now frank has code and a village code will be different right so now the problem here is if i go to update java if i do a resume again during the time of the get method right now this has code is called by the get method in the app.java right now this particular line got executed now the get method is trying to look for the particular student object inside my hash map table right now uh if we'll go to the student.java right now the hashcode will be calculated again for the get method and this time this result will be different see this is a different hash code if we compare to the previous one right now obviously what this get method will think if i do resume again okay see this get method is giving you null because the get method is trying to find out something inside a particular table which is your map table which is this table inside which index it needs to find that is basically calculated by your you know what we call that by your hashcode and in this case the hashcode which came for this particular object student was different than the previous one when is try to enter that so right now it basically looked inside that particular student object inside a different uh you know bucket and obviously did not find that particular object that's why it returned me null so basically it is not looking inside this 10th bucket right now that was the problem and that is the problem right now so if i do resume it obviously my program will be terminated so so the basic uh take away from this example is basically i'm able to change the object state that is basically making the difference so this student object if i'm using it as a key in the hashmap i have to make it immutable so to make it immutable i have to make it final the class should be final and basically this particular variable should be final so i'll i'll just need to make it final and of course the setter method i don't have to give right so i'll remove the setter method right now this particular class is right now obviously you know it's a immutable class this particular name field cannot be changed and that's why right now it can be happily used as hashmap key so nobody can tempo our hus map object so right now if i'll go to app.java right now you can see line number 17 is complaining it is saying that hey you cannot use the setter method so if i'll be removing this particular line then our our problem is solved and if i do resume right now you will be seeing that right now i'm getting india as an output whenever i'm doing map.get and nobody can tamper this particular object data right now because this particular object is immutable and once it's constructed right here is data cannot be changed hopefully it's making sense all right so we kind of have a very meaningful discussion for last 20 25 minutes so right now i just told you one reason why the particular hashmap key just like student this particular class if it is getting used as a hashmap key then it should be immutable in nature so that the content of this particular class will never be changed and we can safely use it as a hashmap key uh so that whenever any lookup operation will be done we will be will be sure that we will get the correct value from our map if it is not immutable then obviously the hashmap value can be changed uh this particular student object can be tampered by using the setter method and i have told you how basically that that particular thing worked your interviewer might counter you okay can you tell me a few other advantages uh of making a particular hashmap key immutable so also he can tell you like okay so basically all your uh all your hashmap key candidates just like string double float integer whatever they all are final they all are you know immutable then how do you think that's basically making a difference if you talk about hashmap performance then the answer to that particular question is um basically the hashcode caching and i basically made a video a few days sorry few years back on hashcode caching i'll just give you the link in the description on or in the i button right there but the answer to this particular question is if our object is immutable just like our student object here i got my name variable if my student object is immutable i'm sure that this name will not be changed in future and if you talk about the hashcode if you see a see my hasscode method the housecode is getting calculated from this name variable okay so if the content for this particular name will not be changed the hashcode for this particular you know object i'm calculating using this field so that you know my hashcode also will not be changed obviously if the name content will not be changed my object hashcode will also not be changed because the student object has scored the way we are calculating by using the field of this particular class called student so in a in a map okay imagine a map the hashmap in the app.java will go here so inside the map when we create a map and when we try to put something to the map and when we try to get something to the map we know that the hashcode calculation needs to be done again and again right i mean when we are trying to put something to the map the husker method will be gets called when we try to get something from the map the husker method will be get called now the thing is that the has got basically getting calculated again and again during the time of retrieval and during the time of insertion so basically if you are using immutable objects as hash map key for an example the student object the student object that you are trying to insert to the hush map whenever you are doing map.put up student if you go to this particular student uh this particular class as this class is immutable then the hash code will always be remain same for the key okay let's say for this student object okay once you once you create a student object for that object the hashcode will be consistent the hashcode will be same obviously for for for this particular variable name if you are going to calculate uh the hashcode for the name for 500 times the value will be same if you'll be doing name.hasscodename.com for 500 times the value that you will be getting will be same right so if the value for this name you are getting same whenever you are running the housecode method then there is no need to calculate the code for this particular variable or for this particular object again and again because any time you are going to calculate the hashcode for this particular name variable is going to be same now imagine in your app.java whenever you are trying to put something to the map okay let's say you are putting this student object okay so basically when you are trying to put this particular student object the map will do what the it will calculate the hash code for that particular object and let's say the high score is generated as one zero one then whenever you are trying to get whenever you are trying to get that particular object from the map just right here okay again the get method will do what internally it will call the house code method again because you need to look for that particular object where it is there inside the map table and again the hashcode is it needs the hashcode to look where that particular object is there now the hashcode need to be calculated again but hold on we have already calculated the house code for that particular object right when we are pushing the data to the map table whenever we are inserting the data to the map table we have already calculated the husker right so no need to calculate again whenever we are trying to look off that particular value whenever we're trying to retrieving that particular value we don't need to calculate the house code again because it's already been calculated so we can basically cache it that's what we call high score caching once the hash code is calculated cache it to somewhere so you don't need to calculate the house code again and again use the cache value uh instead of running the complete hashcode method again so if you talk about all your uh you know wrapper class objects just like integer turbo or if you talk about your string object once you calculate uh the string object hashcode the hash value of the string is getting cached or the hash value of the integer is getting cached because you know during the time of insertion if the hash value is calculated when when we're trying to retrieve something from the hash map we don't have to calculate the house code again because the hashcode is going to be remain same because that is the immutable object and that's the reason here also in our case we made this particular field uh in a final and this is our immutable object so obviously we can also implement our casting implementation just right here so that once the house code is calculated during the time of putting the data inside the map we don't have to you know run the complete has code method again to calculate the hashcode during the time of the retrieval of that particular object from the map if it is making sense then that's good if it is not making sense i will be giving a particular video where i only spoke about this particular thing the caching stuff i'll be showing you that particular thing on that particular video so i'll be giving you the link in the description and also in the i button above you can learn about the hashtag casting more in that particular video so right now let's jump to the next question [Music] all right so now let's go for another question which is very important and this is the question that i asked you in last video also so now your interviewer will ask you okay i i got everything that you are talking about that's fine but tell me one thing if you'll go to your immutable class which is your student class right here right here in this class you have declared it as final so how do you think that this particular final is making a difference so is it really mandatory that your immutable class should be final let's say if i want to create a class and i will not make it final then what will happen okay now even you know if i'll remove this final object still i'm sure that you won't be able to change this particular data so right now you can see from the student.java i just removed the final keyboard so my student is student class is not preceded by a final keyword if you come back to your app.java right now also this particular program should work fine if i'll do run it i'm getting india as a output whenever i'm doing map.get of student but if you want to change the particular student data this is my student class right this class is immutable okay so right now this particular class is not marked as final okay so do you think you can change the data for this particular student uh in the app.java i have not written final there so can you do student okay which is this object and can you do student dot set i don't have a set of method so how do you think you are going to change the data for this particular student right this student was previously the name was avilash now i don't think you have a setter method there inside the student class and you will not be able to change the data for this particular student name to something else then uh it won't it this particular you know object uh will not be changed so it's still a immutable object right and how do you think making a final here making this class final here is making a difference what happened if i'll not make it final this will basically test your polymorphism knowledge and which is a very nice question so let me let me show you an example that how basically the things can be changed okay so if i'm not making this class final then obviously i can i can extend this particular class this class is eligible for inheritance so i will do what this class is your immutable class let me write your emu table class here now this this class is immutable only the thing is that we have not given final here rest of the things the variables are final we don't have any setter method rest of the things we have taken care right so if i'll create another class which is gonna be a mutable class let me say fact student new table okay this is a mutable class this data can be changed right i'm creating another class here and what i'll do you know i'll extend this class to student class which is a immutable class so right now your fake student mutable is extends to student class so what i'll be doing first of all it is giving me a warning because i don't have any constructed here so i'll be adding a constructor so in this constructor i won't be doing anything i'll be basically calling super.name so you should be knowing about the uses of super so basically whenever someone is going to create an object of hex student mute table inside this constructor basically you know i will be calling the superclass constructor and will pass the same variable to initialize this particular name inside the student class so for an example if i will go to app.java right now there are so many things well let's not use this app class right now let me create a new class called app1 and i'll be using that class from scratch so app1 class let me remove this app.java so right here inside the app1 class if i'll have a main method now imagine if i'll be doing uh what is the new class that i have created hex student mutable right so here i'll be using fake student mutable let's say student mutable object or something just like that minimize this is equal to a new fact student mutable okay and here i'll be giving some data as a village okay the student name is a villa so right now what will happen when this particular constructor will be get called it will call uh i mean it will the flow will come to here to this particular constructor now this name will be of the last now it will call the superclass constructor so now here also uh the name will come as a vlast and it will you know initialize this name right the student class name to avilash so the super class name will be variable name also will be initialized okay no problem so what i'll do here i'll just do a trick here okay i'll just tell you what i'm going to do so this is the class this is my new table class let me write mutable guys you have to practice this once okay so if it is i don't think it will be confused for you it's so easy and you guys are so smart to get this particular thing but if you are finding it kind of okay what this guy is doing open up your laptop start coding the same thing and start understanding then it will make a lot of sense right so okay right now i have done nothing simple thing one class i have created extend it to the student class okay student is my immutable class and this one is going to be my mutable class okay so here i'll create a variable private string fake student name okay and when this constructor will run i'll initialize this pack student this dot factorant name uh is a ql2 name okay whatever the name someone is going to pass to this constructor obviously i am going to call the superclass constructor here and initialize the superclass name this this class variable also will be initialized and if we go back to the previous class okay which is my soft class here also i got one variable called fact student name and this variable also i want to initialize so i'm doing this dot fact student name and i'm also going to initialize this particular variable of whatever name i'm getting here with the constructor so right now if i will be going to app.java can i just do a debug once so not needed but you know just to be here on the same page so whenever i'm calling this particular constructor called fake student mutable so if i'll do control s if i do right click debug as java application you will be seeing that switch the flow will come to here it is inside the line number seven so let me go to the peg student mutable class here let me give a break point in the line number nine inside this constructor pack student mutable and also let me go to the super class constructor which is student class constructor and also give me a value i mean give me a break point here so if i'll go to the app1 dot java if i'm gonna do resume first it will come to your sub class which is fake student mutable class this constructor will be get called now it is calling the super class constructor if i'm gonna do a resume first it will go to the super class constructor right now if i'll do step over now this this dot name will be uh you know set to this particular name if i'll hover here right now this name is set to available okay the student class name is right now set to a village if i'm gonna do one thing in my pack student mutable do i got a break point here let me give another break point here let me go to student.java my flow is here in the line number 10 already this name is initialized which is there inside the student class now let me do a resume again now it will come back to the spec student mutable class now this pack student name also will be initialized with the same value right so if i'm gonna do a step over here you can see the fake student name also is initialized with avilash so if i'll if i'll open up the name the name is basically available and if i'll open the current object this now both the name variable of the previous class the super class and also the pac student name both are initialized with avilash this thing is making sense right let me resume i hope we are on the same page let me go back to the java perceptive now we got one constructor here now in this class as this particular student class is not marked as final so that means i can override the getters and the setters right now it it doesn't have any center because it is the immutable class but it got getter method right so let me do one thing let me go to text student mutable my mutable class and in my mutable class i will first of all override the getter method where is that getter get name okay i'm getting a override option i'm gonna override it and here i'm not going to return super class get name i'm gonna do what return pack student name whatever the name that you have initialized with that name only i'll be returning you here whenever you are going to call get name because i am initializing the fake student name as the same time whenever i'm initializing my student class uh you know name variable click here student class name variable will be set to this how it will be set it will be go through the pack student immutable this constructor we're on the same page right okay so very simple thing guys i'm just trying to explain just making sure that everyone who are watching this are on the same page few of you might be gets more bored with all these things because why i'm repeating but i feel that people who are just starting learning java they're also in the same place so just my intention is that okay that's why i'm repeating i'm sorry okay so now the get get name we have overwritten from the super class now let's do one thing okay this is a immutable class in my mutable class i can have setter method also right i'll do control one let me generate a setter method and i only want a setter method so i'll do it i'll just generate a setter method here okay using this setter method i can change this particular variable okay and obviously this particular variable is not uh you know uh final so this particular variable can change so now you just see a scenario with this particular class i will be breaking so many i can break so many thing right as your student class is right now not final as this class is not final right now i am able to override okay i am able to override this functionality get name just right here and i am just changing the get name behavior right now the get name will be returning this particular class uh you know variable which is fake student name i'll just tell you how it is gonna make a difference now you see i'll go to app1.java okay i'm creating a fake student object here okay i'll come back to this later right now let's create a hash map so hash map key value pair now your key will be let's say student object right previously the mutable one the key should be always mutable just now we have discussed sorry key should be always immutable just now we have discussed so the immutable object is student so let me go to app1.java let me just write student here and the value is less this can be anything let me go with string and let me say a map is equal to new hash map all right so now we created a hash map which is going to take a student object as a key so i'm going to create a student object here let me create a student object student student is equal to new student okay and let me say um the object is of elash this line i'm right now not using if you want you can comment this out this student is gonna be my key so i'm gonna put this uh put a value to this particular map so map.put and i'm gonna pass in the student object just right here copy and paste and the value will be a string so let me take uh india as value right so right now i'm putting something into the map okay right now obviously i can get things right i can just do this out and i can do map dot get of uh this particular student object because this is my key right so whenever i'll be trying to get the value i'll be getting india as a as as a as a return type okay and also let me write another log just to give some notation here that my program is terminated cool so right now if i run this application obviously you know that you know the student class you know this key i have used here the value for this is india so if i'll run this i'll be getting india as output nothing fancy here okay so right now i'll just tell you this particular class is not marked as final right there there where we are lagging so the way we can change the implementation for this class right now in the app.java i'll come to here right here what you are doing the further key we are just giving a student object right our student object is this one okay now my student object also got a subclass right my student is the parent if i'll go to here my uh there is a class called fact student mutable which is extending to my student object so i'll go to app1.java right here in the line number 11 this new student right this new student part uh i i'm not going to initialize the student object directly rather what i'm going to do i'll remove it i will uncomment this line so basically i'm creating a fake student object just right here and this is a mutable object okay so this particular object i have initialized this right here i will copy this i will put it just right here okay now my parent class which is student object let me say student ob say mute immutable okay this is a immutable object okay and let me also change this uh key just right here okay cool and also in the get method also let me change that to student objective mutable okay that's gonna make so much sense whenever you're reading it now your student object your student object immutable is right now containing a mutable student object if you click here right now this class is mutable right so basically your parent p is equal to new child your parent can store the child class object inside that reference that's what i'm trying to do i have created a fake student mutable class object which is a child class of my student object student is the immutable class fact student mutable is a mutable class so right now i've assigned this object just right here and this object only the student object mutable i'm using as a key in the hashmap i can do that right because my hashmap is saying the key will be student object okay now okay i'm just giving you the student object here only so the student object immutable click here this is only having the student reference right and obviously this particular object is right now this particular reference is right now pointing to a mutable object right it is storing a subclass object internally so right now now no problem if i do uh run this you will get india as a output but now here i can trick my application what i can do once i insert uh the value to the map here what i can do this is the object okay see in my map i'm putting the student object immutable click here this object is this one this is my student immutable class object now this object is containing student mutable object click here this is containing this guy right and this is a new table class and this object can be changed the state of this object can be changed so let me change that so with this reference student mutable object i can do student mutable object dot set see i got the setter method here for of this particular class okay so set fake student name and i'm gonna set the fact student name to let's say right previously it was obvious right for this only the high score was getting calculated well i'm gonna change the content of that object i'm gonna say to xyz or i'm gonna say to priya okay do control s right now if you're gonna run this you won't be getting you won't be seeing anything fancy uh india that's because whenever right now the map is trying to put something or the map is trying to get something basically whenever it is trying to put something the object is this guy uh which is the student object so inside our student class object we got the hashcode and equals method okay and the hashcode and equals method has not been overwritten inside the peg student emu peg student mutable class that's why the parent class has code and equals method is getting called inside my student class i got the hash code and equals method just right here but what i'll do right now so that's why you know if we'll go back to app1.java right here it is this particular object this particular reference is holding this object so in this object we don't have any hashcode and equals method that's why the parent has code and equals method is getting called in the runtime so right now i will do one thing i will just create a housecode in equals method just right here and after that you know after that you know we'll be in a horrible situation if i'll generate the housecode and equals now the hash code and equals are generated you can see the high score is getting generated from the fake student name if i'll do control s right now if i'll go to my app1.java right now if i'm going to run this application you can see that i'm not getting the data okay now i'm getting null here my hashmap property is broken that's the counter response you can give it to the interviewer that well if i not be making my immutable class final then somebody can extend to my class and can change the behavior of that particular class and the place where we need a immutable object just like in the hashmap or any functions if you have which accept a immutable object there someone can extend there someone can create a class which is mutable in nature it can extends to your immutable class then it will give your mutable object where it is asking for the immutable objects just like here just like here we we trick our application our hashmap is asking for a student class object this student is a you know immutable class object but this object is not final this class is not final that's why somebody has extended this particular class and do whatever it needs to do just right here he has written some kind of code and right here what he did he just changed the behavior of the mutable object and what he did in the app1.java as a key he is using what this guy student object immutable is using the immutable object but as this immutable object is extends to the mutable object that's why he is he can basically assigning a mutable object reference which is the fake student mutable object reference okay and he has already done the haas code and equals okay and obviously he got the setter method and because of that he'll be able to change this particular peg student name and that's how he is making things horrible just right here in the upward.java so whenever basically we are trying to put something into the map it is going into some bucket then by using the setter method he's changing the value to something else and now whenever we're trying to get that particular object from the map obviously uh we have changed the content of the previous object that our map is holding so obviously the house code is not getting calculated and my hash code concept of the properties are getting broken okay do this example for one time and it's gonna make a lot of sense if you have any questions to this particular thing put that in the comment section only the polymorphism and only uh the map concept that i have used here if you have any question put those questions right in the comments section you can go to my facebook private facebook group which is selenium express dash support you can read your questions just right there you can also go to my website uh www.seleniumexpress.com you can let me know your code is just right there and i'll be able to help you if you have any other questions just let me know on this particular immutable concept that we have discussed it's pretty important and that's why i have to make sure that my student class which is a mutable class i have to make this class final all right hopefully this is making sense okay cool right now obviously we'll be getting error here in the facts and mutable because because you know obviously we cannot extend to our student class and this extends stuff will not work if we hover over here it's going to say remove the final modifier from the student we are not going to remove the final modifier from our student class which is immutable class because by knowingly we have given that final keyword before our class which is a mutable class so the type of text student immutable cannot be subclass the final class student making sense all right try it for one time [Music] [Applause] all right so before i wrap up this particular session okay there is small a small two questions i will show you might be some time they will ask you in the interview the first question will be let's say you got a string here string str string is immutable in java i'm sure that you know about this let's say i got a string here string str is equal to avilash and right now someone is doing what someone is trying to print out this string let's say sis out sdr then what will be the result of this okay don't look at me like this like i i know that you you understand this that'll be the answer for this but now the question is if i'm gonna do str.substring and if i want to find some part of a particular string let's say i want to only print a v here then i'll be using a substring method so if you're new to substring i already got some video created on soft string which is very very important you go and watch that very important for interview perspective let's say if i want to use soft string or if you if i want to do some concat if i want to do concat with savilas i want to add panikrahi which is my surname why should i add my short name i should ask you guys to do something for me right now that says subscribe okay sdr.concad of subscribe so obviously subscribe please subscribe to our village or selenium express uh please do that guys i really mean it i always don't say you that but i i really mean it i mean uh your subscription your i mean the time you criticize your time you give a valid input to me that's actually you are giving an input to my uh to me as a person right that really means to me your thoughts your subscription your like your dislike your responses basically i do care it a lot right so please show me responses either by hating it other otherwise by loving it or by letting me know about myself as a comment i'm not telling you that go and say me good good things there but also i'm not telling you that you should start uh you know criticizing or abusing somebody for no reason you know just responses some responses we we we are professionals right uh i mean you can at least spend one minute to write a response to me if you do care about me and my channel if you are my uh you know valued customer uh you are not my customer you are my family so how can you can be my customer right i'm just teaching you something for free on youtube okay don't talk about the money that i earned from youtube okay your salary that you get at the fresher is more than that youtube money okay so anyhow line number 10 i'm doing str.con cat here let's come back to the topic the only the point was just give me a thumbs up or thumbs down uh to this particular video if you're like if you're liking and enjoying it and just do subscribe and hit that subscription button okay now come back to this particular you know um code and just tell me in the line number 10 if you see the piece of code that i'm having and in the line number seven uh the piece of code that i'm having do you think the str object that has been created here when i'm whenever i'm trying to concat something to that str object it is basically creating a new object or is basically modifying the same object so right now if i'll do str.concat and basically if i'm gonna say str one and i'm gonna print both str and str1 let's say this out tr one so you know the result this is whatever i have initialized with avilash and str1 should be available subscribe subscribe to our village please do that so so there you go avilas and avila subscribe so we got two different string here in front of us but right now so am i creating a new string or this str and str1 are belongs to the same string first question is that and obviously this str1 and this str are two different string even you use this um you know double quote or you may use this new string method okay don't we get confused with this constructor stuff right if i if i if i uh create my string just like this this str is a different string this str1 is a different string if you run this obviously you'll get a villas and i will subscribe but if you'll go to the concat method internally you will see something internal implementation of concat now you see um when you do a concat in line number 2034 the concat method is returning a new string object so basically it's constructing a new string so the concat method is accepting a str whatever you are passing in and is returning a new string by using a string constructor this is a different string constructor we're inside the string class right you can do ctrl o and just start typing string see how many string class constructor we got uh we are using right now the string constructor which with basically texas string um i mean this this constructor we have used but they are using a different constructor here to create a new string okay so there we go uh basically the concat method basically create a new string not only the concat method if you'll go and look for the substring method or any other method uh you can see the substring method written on a new string okay it's basically creating a new string by using the string constructor so basically the string is immutable class and sometimes they will ask you like okay if i will be trying to uh concat something with your string or if i if i'm trying to you know get a soft string from your string from your original string so do i do i create a new string or this basically gives a gives me back the same string obviously the answer you know right is basically creates a new string so uh can i do does can i do uh dot hash code here you can see the str score and str one has score they both will be different if i'll run this see the hass code are different okay but what about instead of string if i'll be using a string buffer so if i'll do string buffer uh uh let's say my name is equal to new string buffer and if i will be creating a string like a village okay and if i'm gonna print it this out my name and again i'm gonna add something to my my name i'm gonna do a paint and here i'm going to say vani graha which is my surname and basically uh what i can do basically i can end this up this is going to return me a new uh in a string buffer and i'm gonna say my name updated and i'm gonna print both these variables this out my name updated i'm i'm printing here and my name i'm printing here and obviously here it will be a village and here i'm updating uh the same object uh with panigale included so if i'll be running this you can see the first one is a village the second one is my concatenation value right of elastic right but the thing is that the string buffer is a mutable object so whenever you do a append my name data page is not returning you a new string buffer object rather it is returning you the same string buffer object i will be proving it use dot hash code here and use dot hash code here so you'll see that once the append is also done it is returning you the same string buffer object so if you'll be running it you'll be seeing the same hash code just right here hopefully this makes sense right so string buffer is a mutable class but string is an immutable class even though you do a concat or um you know a soft string to your original string it always returns a new string because it's immutable all right so guys this is it for today's tutorial i hope you are right now feeling comfortable with immutable and immutable classes immutable objects and different kind of uh you know pros and cons of immutable objects immutable objects with hashmap is a key and different interview questions just like this i am sure that you will take these questions i mean in a confident manner whenever you'll be asked this question in your interviews and wishing you all the best and i'll see you in the next episode with some more interview questions and if you have any doubts obviously do let me know with a comment and also join my facebook private facebook group which is called selenium selenium that's uh sorry selenium express task support and you can post your queries and questions right there and also if you like you can follow me on instagram my instagram id is selenium underscore express i hope so that's correct so yes so i'll see you soon till then bye bye take care and happy coding [Music] foreign
Info
Channel: Selenium Express
Views: 10,672
Rating: 4.9102244 out of 5
Keywords: Why HashMap Keys are Immutable?, Java collections interview questions, Immutability & HashMap, hashmap immutable key, how hashmap works internally, hashmap, hashmap internal working in java, hashmap in java, custom immutable class in java, java immutable vs mutable, immutable classes in java, core java interview questions, java interview questions and answers for experienced, top collection framework interview question, java collections, java collections questions for experienced
Id: Y1uGGTrBYKw
Channel Id: undefined
Length: 67min 53sec (4073 seconds)
Published: Sun Mar 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.