Java Generics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to this lecture we're now going to dive deeper into generics and you've been using them so far in this course while you were working with collections but we need to dive a bit deeper to fully understand how they can be useful in your Java code now several lessons ago when I introduced the ArrayList you saw that if we create an array list and don't specify the type parameter meaning you know in those angle brackets if we don't specify the kind of data that can go into that ArrayList we could run into some trouble now let me quickly revisit that before we move on to the specifics of generics here I have the project more generics I created sort of on the fly and you can do the same I have a package here called client and I create a class called application with the main method in here so let's just quickly define an ArrayList and I'll call it my list is equal to new ArrayList notice that I didn't use the type parameter so you know those angle brackets I'm not specifying them here let's do the ctrl shift o to bring in the import notice the Java is giving us a warning if I hover my mouse on the ArrayList notice it says ArrayList is a raw type references to generic type array list should be parameterised so it's basically saying that this is a raw type be careful how you use this thing and what it's warning us about is I can add anything I want into this collection I can do my list dot add and then put in the word hello all right I could do that on one line and on the next line I could do add an integer on the next line I could just go ahead and you know add a a boolean such as the value false so I'm adding different datatypes into this collection and it's warning us that hey you're using the raw type meaning that anything that goes in here will be considered an object it won't be considered the type that you intend to put in here in other words if I want to extract one of these one of these data points if I do my list dot get and I specify the 0th index position and I assign it to a variable we know that it's a string and I can say my vowel is a variable name notice that it's complaining however your mouse you are saying type mismatch it's basically saying hey what do you mean that this is a string right it doesn't know the datatype so we have to literally cast it we have to specify that this is a string and now it will not complain but here's the thing though let me copy and paste this on the second line and I'll call it my valve two and I put the index position 1 notice we've got a problem here at the first index position that's this guy right here the second value in this list we know that it's an integer but Java has no way of figuring out what data is has been added to this ArrayList and we can you know we're basically fooling it by saying there's a string in here and we are taking the value casting it and putting it here even though it's actually an integer so again the error hover your mouse on ArrayList it's saying ArrayList is a raw type reference just a generic type ArrayList with the angle brackets you know II should be parameterised so if you control click the class let's go to the top notice that this class is a generic class look at these angle brackets okay so it wants us to specify what kind of data is going to go in this class that's why you see these warning Z's yellow you know squiggly lines underneath so let's give it that let's specify the kind of data that's going to go in here string and now that error up there went away right though that the warning is no longer there but these two guys are no longer allowed okay we can't put in an integer into a string and we can't put in a boolean into a string collection this allows more type safety now the java language is all about types okay classes are considered types abstract classes they're considered types interfaces right these are all considered types and what I mean by type is that you can you know declare a variable and it's data type is going to be either a class or an interface right you specify the type for that data so this is the variable and we're specifying the type and since Java is all about types it was designed to be type safe in other words it's sort of babysits the developer to make sure the developer knows what the data type is that they are working with right so for example if the developer you know assigns an integer some number to a variable that is of type string the Java compiler is immediately going to bring that up it's going to complain immediately while you're coding up right here in your IDE so that's actually a beauty of type safety rather than finding the the errors during runtime type safety is ensured during compile time now because there is this babysitting going on with regards to type safety the Java language previously seemed overly restricting with what a developer can do with object-oriented programming so generics were finally introduced in Java version 5 to allow more flexibility when designing your programs generics keep the promise to allow the developer to be flexible without sacrificing the benefits of type safety ok and that's exactly what we see here right take a look at the ArrayList class ctrl-click right it's flexible enough to allow any kind of data type to go in here right we specify the type parameter we're specifying here that you know a string can go into these angle brackets I can you know define my own user-defined class that we saw earlier and I can give that class in these angle brackets so the ArrayList class allows flexibility on what can go in here but at the same time it ensures type safety that's the beauty of generics this is considered a generic class the ArrayList so is the hashmap and some of the other classes you've work with so far in this course so now let's go over how to create a generic class and then we're also going to talk about generic methods generics is an advanced Java syntax so this is really the only part of the language that's sort of holding you back from going knee-deep into the Java native libraries reading through the ArrayList code reading through the linked list code and so on so once you understand generics your fear of reading Java code will certainly be eliminated okay here we are back in the application class I've gotten rid of the code that we had there before and now we're going to talk about how to create a generic class and then I'll move on to creating a generic method so right click here in the same package client right click and go to new class and we're going to create a class called container let me define two variables here they'll be able type string and I'll call it item one and string item two let's also add a constructor and of course we need to assign the different fields so for this class is only capable of working with strings let me define one more method so we can do something with this we'll just say print items and we'll specify what item one contain what item one is and we'll do the same for item two so this class right now is only capable of working with strings what if I wanted to make this class work with integers or you know boolean x' or you know some other number or even a user defining to type for example some other class instead of specifically saying that the item 1 is going to be a string and item 2 is going to be string I can change this to be object okay and right now we're not using generics right I haven't used those angle bracket syntax anywhere I've changed the type for these variables to be object and nothing is complaining so far because string is in fact an object so it's not going to complain let me also change these to object and change this to object okay now I can use this in somewhat of a generic way I can say container and I'll just call it container is equal to new container and then pass in for example the number 12 and the string hello okay both of these are children of the object class the this integer as well as this string is in fact an object everything is an object in Java right so it's not complaining at this point if I was to add a getter to this class I just quickly go to source and generate getters and setters and we'll just select all notice that these get item one and get item two it returns an object so if I wanted to use if I wanted to say Container dot get get item one and we know that item one here is an integer if I do int you know my bar it's not going to allow me to do that it wants me to specify this to be an object right we've seen this before with you know working with collections so this class is somewhat generic I can use it to put integers doubles you know any user-defined type but it's not type safe we know item one here is an integer but if we take it out as a string if we cast it as a string datatype the Java compiler would not know the difference as far as its concerned everything is an object so whether we cast it to an integer or a string it doesn't matter notice that it's not complaining even though we know that this is an integer so how would we make this class generic we use the angle brackets and specify the kind of data that this will have the types of data that this container will have and we can call it I 1 and I 2 and so this I 1 and I 2 could be I 1 here and I 2 here so now item 1 and item 2 is capable of being any kind of object whatever type parameter is used okay and the same thing goes for for these arguments we have to put I 1 and I 2 okay so now the constructor is passing all of these others they're going to complain because an object we need to we can't just be an object it needs to be using this i1 or i2 type so we need to change this to I 1 and change this to I 2 and now this class is completely generic okay if we go back to the application class if you hover your mouse it's going to say containers a raw type so we're using the raw type version for this class because we're not specifying the type parameter that's what the warning states so let's indicate that these are going to be integer that's going to be the first argument and string is going to be the second argument as you can see right here is the first argument and this is second argument item 1 is going to be an integer item 2 is going to be a string and at the constructor we need to make sure we use the angle brackets to specify that we want to use the parameterised types that we are specifying here if we don't repeat those angle brackets it's still going to treat this as the raw type okay see it's saying container is a raw type so we need to specify the angle brackets so that we're not using the raw type now we can say container get item 1 and all one thing I forgot to change let's go back to item 1 the get item 1 method it's not returning an object it should be returning I won okay and same thing put down here item 2 should be i2 and now this can enforce the proper types I can say that the value for item 1 is of type int and I'll just call it Val 1 and notice that it's not forcing us to cast it to anything it understands that it's an int and same thing with the second field item 2 is not an integer right item 2 is not an integer and it knows it this is compile-time type safety going on here is checking for us making sure that we don't make a mistake all right it's saying type mismatch cannot convert from string to inte okay because we stated that this is a string right the second type that is being used in classes of string when we try to get that filled item to its complaining and saying a this is not an end this is a string so we need to change this to a string and now it's working fine so do you see how generics keep the promise to allow the developer to be flexible enough right we can put anything in here we can use this container to save any kind of objects whether it be strings doubles or user-defined classes we can use this container for anything as long as we specify the types so generics keep the promise to allow the developer to be flexible without sacrificing the benefits of type safety issues related to types or highlighted at compile time rather than runtime so I showed you how to convert a you know a sudo before it was a pseudo generic class it wasn't really a fully generic class now this class is completely generic okay it's based on whatever types is passed into the into the angle brackets so the container is a generic class and we can pass in any kind of data type in here and that's going to take the place of wherever I one is and I too is so here integer is going to take the place of I 1 and string datatype is going to take the place of I 2 so wherever we're defining variables or referring to this I 1 and I 2 in the method definitions and you know the types for the parameters everywhere where you see I 1 and I 2 that's going to take that place respectively in that order as we're as we're passing it here in the angle brackets okay so that's a generic class now let's talk about creating a generic method outside of main I'm going to create a method and we're going to call it Union and it's going to be a static method and the return type is going to be set and the method name is of course Union and it's going to take two arguments one is set we'll call it set 1 all right that's the parameter name and this is the datatype set and you've already seen sets you know from the previous lessons the second argument is set to ok and what this is going to do is going to Union both of the method both of the sets together and return a result so if set one contains one two three four five and set two contains six seven eight nine ten the return value of this set is going to contain the numbers from one to ten and remember sets do not store duplicates so if there's any duplicates it's going to disregard them and we're only going to get unique values in the returned result so let's just do a quick control shift o to bring in the import for the set interface and I'm going to define a variable in here called result that's going to be of type set and we're going to do new hash set and you're probably noticing that right now this is not a generic method to the argument of hash set when we're instantiating this hash set we're passing in set 1 so that result contains the values that are in set 1 let's do the control shift o to bring in the import for hash set and now all we have to do is result dot add all you've seen this from the previous you know collections lessons the add all method adds all everything from another collection so we could just pass in set to and after this line the result variable will contain the data for both of these sets and it's going to disregard duplicates so we could just return result and now this method should be compiling so notice all of these warnings I'll hover your mouse and it's of course saying you know we're using the raw type we're using the raw type saying that on pretty much all of these lines and that's a problem because if anyone uses this method without the regard for the data types you know one set can contain strings and the other one could contain integers it'll still be able to add that to the result but if we try to get those values and do stuff with it we're going to have trouble okay because we're going to be iterating over things that we don't even know what those you know data types are and we can have class cast exception issues you know exceptions taking place during the casting process so to convert this non-generic method into a generic method there are a couple of things we need to do the first thing is we need to pass in those angle bracket syntax to the parameter variables so set one is of type set with angle brackets with some value this unknown type right now I just gave it the variable II just like in the container class how we gave the variable I 1 over here I gave the variable e to represent whatever data type is going to be used for this set and then for the second argument is also going to be e and wherever e is used in the body of this method right now I haven't used it wherever it's years it's going to take that data type in the definition of this method so right now it's giving an error because right now it doesn't know what E is hover your mouse over here and it's saying 'i cannot be resolved to a type it just doesn't know what E is so we need to actually define the type for E and another thing is if this is taking in two sets with the data types of E then it better return the data type for e so the return type force for this method is also going to be set with the e data type and we're almost there we're not done yet with this with the signature of this method there's one more thing that we need to do we need to define what E is in this method all right yeah I'm not talking about you know defining whether it's going to be a string or an integer or some double or some other data type we want this to be generic we want this to be usable for any kind of data type and to let this method know that hey we're going to use you as a generic method there's a very important piece to this and that's going to be defining what E is and where do we define where E is we just define it out here like that okay this is going to take a little getting used to when you look at this code you're going to see all these ease with angle brackets might be can using at first but it's important to understand that over here we need to specify that hey we're going to be using this e inside of the method body and method signature and we specify that right here right before right before the return value for this method right this is the method name this is the return value for this method and then over here we are specifying that we're going to be using e inside of this method if I change this to some you know T we still have a problem it doesn't know what E is all right it's showing the red squiggly lines underneath these e type parameters so we have to specify E out here and think of that as we're sort of defining that E has a significance inside of this method definition as well as a method body so the rest is actually very simple the set that we're referring to here also better utilize the same data type and of course when we're defining the hash set we need to also specify e right here okay and again as I spoke about a couple of lessons ago after the new keyword if you're using Java seven after the new keyword when you're instantiating a particular collection or generic class such as the hash set we don't need to repeat the contents of the angle brackets we can leave them out right like I'm doing here for container I left out from the angle brackets this integer and string because since I'm defining them as the datatype for this variable Java is smart enough to know that we you know we're going to have these same things inside of this angle bracket so it's just a little less syntax for the developer which is a good thing because if we had like ten different data types inside of these angle brackets we'd have to repeat them for you know after the new keyword and that would be a really long lot of code basically so the Java community for version seven had this upgrade that you don't have to repeat those data types for the second set of angle brackets and that's why over here I don't have to repeat in the second set of angle brackets this e alright but for the sake of clarity I can do that if I want to okay and for this example I'm going to leave it here and that's it this is now a completely generic method and if I want to use this method I can create two sets we'll call it a set of strings and we'll call them I set one is equal to new set of strings and of course the second part needs to be the actual implementation this is the interface we need to actually have the implementation you should know this from the lectures on object-oriented programming so if we specify the actual class hash set and now let's give my set one some data we'll give it you know some random words I'm just going to call it first and repeat that here a couple of times first second and whatever okay and I'll just copy paste this to save time for set to all right there's going to be called my set - this is also string and it's going to have instead of the third word being whatever I'm just going to call it computer okay so a quick quiz what do you think is going to be populated in result when I Union set one and set two using this method what do you think is going to be returned when I call the Union method passing in my set one my set two to this method invocation will I expect four words to be populated using this Union method and there's going to be first second whatever and computer because this first and second here are going to be duplicates and the results hash set is going to ignore those when we try to add in the second set because sets do not contain duplicates right that's just a quick revision you should already know this so I could just call Union and pass in my set one and my set two just like that the return value for this I'm going to store it in a variable called result set now over here it's giving us a warning hover your mouse over the set keyword thing we're using the raw type again so all of this hard work that we did would not be of any use to us unless we specify that the data that's coming out of here is of a specific type because when I do things with the values using the result set it's going to consider them all objects so I want to make sure that I specify that it's going to be string data and now to iterate over the result set I could use the iterator and this is another way of iterating over collections instead of the for loop we could use the iterator and every collection class has this iterator and I'll show you how to use it we can do result set dot iterator and now we can use this variable called ITER to iterate over the values in this result set let's do the ctrl shift o to bring in the import for the iterator class and now to iterate over this whole thing we can do while ITER dot has next while that's true it's going to iterate over the values and I'm just going to print out those values will invoke the next method on the iterator so let's hit play to make sure it's working and there we go we have four words that are printed now notice something here notice that there's a warning underneath iterator hover your mouse and saying iterator is a raw type reference just a generic type iterator with the e type parameter should be used so what's it saying here well it's saying that result set contains a list of strings right so because of that it's saying that a result set actually is a list of data that is of type E right whatever that type is supposed to be generic and in other words it's it's a list of type strings and right now we're using iterator without specifying the type of data it's printing data just fine but if I wanted to use these values let me get rid of the print line statement here and try to do something with this so we do it or dot next and if I want to get the value I could we know string right we put strings in there if I define a variable called we'll just call it war I'm getting the value from the iterator by invoking the next method and assigning it to var but we've got a problem notice that there is an error of your mouse over here and it's sync type mismatch cannot convert from object to string okay so when we're getting the data from the result set when we want to loop over it using the iterator we want to make sure that we use a generic version not the raw version right now we're using the raw version and I'll prove it - let's click on control click the iterator class and notice well it's an interface but anyway notice that it has a type parameter it's meant to be used with some data type and it's up to the programmer to choose whatever data type they need to use with the iterator and if you don't use it it's going to give us a warning because later on when we use it down here it's got its going to force us to cast it so I now have to cast it like this and only then it's going to work so to prevent casting and to make sure the type safety takes place during compile time when we're coding we want to make sure we continue to use these angle bracket brackets and specify the kind of data that we are working with okay and now that error or the warning on iterator has disappeared because we are using the correct data type so again what's the beauty of this well if I you know mess up for whatever reason I put integer here the Java compiler is smart enough to know that the data that's returned is not a list of integers it's a list of strings so of course it's saying type mismatch cannot convert from iterator string to iterator integer so when we invoke the iterator method on the result set it's going to return the data of the type or result set which is a set of strings so things are type safe when we use generics and now it's compiling just fine and I could just print out the value of var like that and we'll get the same results so let's hit play and boom there you go it's working as expected alright so we've covered a lot of ground in this lesson I don't want to flood your brain with too much information in just one lesson you should review this if there's a bit challenging and it might be in the beginning don't worry it's going to take some time for you to grasp it 100% but it's all about the practice so make sure you're coding along but the big idea behind this generics thing is we can use them for method definitions right over here we have the method called Union and we are declaring that we're going to be using a generic type parameter and we have to first define it and where is it defined quick pop quiz where is the generic type parameter defined in this method it's right here right this e we're saying that e has a significance inside of this method anywhere where you see e is going to be the type that is specified in the argument and because it'll be passed in as an argument to this method that E is going to be used inside of the body of this method wherever you see e that's going to be the data type that was passed in to this method okay I could have made this I could have made this T all right and then it's good not going to compile because all of these ease it doesn't know what these e's are all right so the type parameter that we specify here is meant to be used in the body of this method now I can have e I can have multiple I can have V I can have Oh whatever I want all of these letters I can specify that each one of these letters will have a significance in this method all right it's compiling right now because we have e here and we're using e it's not complaining even though we're not using V oh gee these are just random letters that I came up with they can be anything they could be you know words you know I could I could just type whatever I can make these anything I want any legal variable but if I use some variable in here or the type parameter in here instead of these angle brackets such as the word hello we've got a problem because Hello is not defined out here this is where we define the type parameters that will be used inside of this method alright and hello we're using it here but we're not defining it out here so it needs to be part of the method definition out here this is where we specify the type parameters that will be used inside of this method now of course it's not going to compile the way it is right now because hello here has nothing to do with e so it's not it's not going to work so let's just change this back to either way it was and let's get rid of all of this other stuff all right so hopefully that makes sense these type parameters you can name them anything you want typically a single letter is used you'll see in the Java API certain letters being used for example the ArrayList has e for element that represents element the capital e you also see a bunch of T capital T to represent types and for hashmaps the capital letters K and V being used K represents the datatype of the key and V represents the datatype of the values for a hashmap over here in our container class that we created write this we're passing an integer and string integer will take the place of I 1 so wherever I 1 is in this class it's going to represent the integer and I 2 is going to be the string and wherever I 2 is in this class it's going to be a string datatype so these are type parameters and they could be words best practice is to use single capital letters that's the convention I broke the convention here just to prove a point that you can really have anything any legal variable inside of these brackets so again back from our object-oriented lectures when I was talking about the fact that a class is a specification it's a blueprint this is a class ok it's a specification to blueprint a template so to speak and and we're specifying that these type parameters are part of this template wherever these are used some data type is going to be replaced there ok this is a specification for what a container is when we use this specification here in our application class we're using the specification we're calling new container we're instantiating a new container and we're specifying that hey this particular instance is going to be using the integer as well as string later on let me just copy paste this down here I could specify a new container we'll call it container 2 this is a new instance and in here I could say that there's going to be a double and the value here is going to be integer so these are two different instances container 1 and container 2 but we're using the same template of the container class and these two values double or integer or integer and string are going to be taking these the i1 and i2 s place respectively okay and this of course is not compiling because double is you know it's usually a decimal number and we have a string so let's change this to an integer I'll make it 300 for example and let's put a decimal like that and now this is compiling so we're using the same specification right same class definition with two different types of data all right and that's what generics allows us to do and you can use generics for classes as well as down here as we did for the methods for classes we define we define the generic type parameters after the class name like we are doing here right this is what we're defining the type parameters that will be used inside of this class okay this is where we're defining the type parameters and over here in application class down here we have a method Union where do we define the type parameters for methods we define them right before the return value this is what this method is supposed to return and right before that we are defining the type parameters that will be used in this method okay so a lot of information covered in this lesson make sure you review it watch it over if you have to these are fundamental generic concepts that you must understand there's a couple more things you have to talk about with regards to generics and I'm going to save that for the next lesson so stay tuned thanks for watching I'll see you soon
Info
Channel: Imtiaz Ahmad
Views: 59,469
Rating: 4.9543228 out of 5
Keywords: Java, Java Generics, Object Oriented Programming, generics, Object-oriented Programming (Programming Language Paradigm), Java (Programming Language), Java Tutorial, Java SE 8 Programmer, 1Z0-808, java certification training, object oriented programming java, oop, object-oriented programming, object oriented programming
Id: 4ZO7uVon-kI
Channel Id: undefined
Length: 35min 9sec (2109 seconds)
Published: Sun Apr 30 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.