Vectors in Java: The 1 Situation You Might Want To Use Them

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you've been programming in Java for a while you're definitely familiar with arraylists but what about vectors and if you have heard of them you were probably just told to never use them but why we'll show the similarities and differences between arraylists and vectors with some quick live coded demos we'll even find something that vectors do that arraylists don't so stick around and find out I also have a full Java course available with over eight hours of exclusive video lessons covering dozens of topics so go check it out so first as always what exactly are vectors in Java vectors have actually been a part of java since the very first version was released way back in the Stone Age of java also known as 1996. this is before Java even had arraylists arraylists were added in version 1.2 so all a vector is is a collection of objects that offers convenient methods for adding removing and manipulating the elements inside it it uses an array behind the scenes as its underlying data structure to hold the elements but it will automatically grow and Shrink that array as you add or remove elements so in that way it's more convenient to use than a regular array now you might be thinking that sounds an awful lot like an arraylist and you're right on the surface vectors act almost exactly like arraylists do so if they do pretty much exactly the same thing why would you ever choose one over the other how are they actually different why do they both exist so let's start going over some of those differences one of those differences is performance let's dive in and write some quick code to compare how long it takes to say add a million items to an arraylist versus add a million items to a vector okay first let's just declare an INT we'll call it size this is just going to hold the number of elements that we want to add to our arraylist and our Vector so we want to add 1 million items to each of those so first let's go ahead and declare our arraylist we'll make an arraylist of integers and here we're just going to call it arraylist equals new arraylist now we want to time exactly how long it takes to add a million elements to this arraylist so first we need to capture the current time at the beginning just before we start adding the million items so we'll declare a long to hold the current time in Millis we'll call it start and set it equal to system dot current time Millis and now we want to add a million items to our arraylist so all we're going to do is use a for Loop for that so for INT I equals 0 while I is less than size so here that's going to be a million then I plus plus to iterate so each time through that for Loop we are going to add the element I whatever I is at that iteration in the loop to our arraylist so at the end of this for Loop we should have 1 million items in our arraylist and now that we've done that we need to capture the system time after we've added those million elements so long end set that equal to system dot current time in Millis and then we just need to print out the difference between the end time and the start time to see how long it took so we'll go ahead and print out so we'll just say added size elements to arraylist colon space and then we'll record how many milliseconds it took so that would just be end minus start and then we'll add on Ms four milliseconds okay so let's go ahead and run this real quick just to make sure it works as we expect okay so it took 44 milliseconds to add a million items to an arraylist now let's show how we would do that exact same thing but using a vector instead and it's going to look pretty similar so to declare a vector we just say list integer and we'll call our test vector vector equals new Vector now you'll notice just like an arraylist we declared it using the list interface and that's because when Java 1.2 came out with the whole fancy new collections framework with arraylists and maps and sets and all kinds of stuff like that they actually retrofitted Vector to implement the list interface so it is technically a member of the collections framework so what we're going to do is the exact same thing we did to this arraylist we're going to add a million elements to it and it's going to be just about this exact same code so let's go ahead and copy and paste it here one thing we do have to change though is that since up here we're already clearing a start variable here we don't want to declare it again we just want to set it to be the current time Millies here right before we add everything to our Vector so of course here instead of adding to our array list we will add each element to our vector and the same thing goes for the end variable here we don't want to declare it again except now our statement here where we print out how long it took we'll say added size elements to vector and then everything else here will be the same end minus start now will give us the total time it took to add a million items to our Vector so let's go ahead and run this a few times and see if we can see any kind of a pattern with the performance between these two collections so here we go okay so it took 70 milliseconds for arraylist versus 126 for Vector interesting let's keep going let's try again 57 verse 195 milliseconds that's almost four times times as long for a vector let's see so we're kind of seeing a pattern here right it seems pretty consistent that adding a million items to an arraylist is much faster noticeably faster than adding a million items to a vector so is that the end of the story here well not quite arraylist might have been faster here but it has to sacrifice something to get that edge over Vector in speed let me show you what I mean let's say that instead of just using a single thread like we were here we're instead going to be operating in a multi-threaded environment so we're going to have two threads try to add elements to an arraylist at the same time and then we're going to have two threads try to add elements to a vector at the same time so let's keep all the code we've got and add another section down here where we're going to use a multi-threaded approach so we'll go ahead and create another list of integers we'll call this one multi-threaded list equals new arraylist we're going to set the start time just like before to be the current time in Millis now there are a ton of ways you can set up multiple threads in a Java program but we're going to do a pretty quick and simple way here now remember what we're going to do is create two separate threads that will run at the same time so they're both going to be trying to add a million items to the same list at the same time so we're going to create a thread we'll call this one T1 For Thread one set it equal to a new thread and here we're going to get a little bit fancy and we are going to use a Lambda to declare what should happen when we kick off this thread now we're not going to dive too much into lambdas in this video but if they have always been a mystery to you go ahead and check out my other video on lambdas here anyway we're going to do a little arrow operator here and then inside these curly braces we can Define what we want our thread to do when we kick it off and so what is this thread going to do well it's going to do eggs exactly what we did before and it's going to go through a for Loop where it adds a million items to our arraylist so I'll just change this to our multi-threaded list and there we go that's it now we want to do the exact same thing with another thread so we're going to copy this and all we're going to do is change T1 to T2 now all this does is create our two thread objects but this code doesn't kick off those threads to actually perform these operations yet all you have to do is call the start method on each thread so T1 dot start and T2 dot start so the start command will kick off that separate thread to perform the work that we've defined here and here but we don't want to continue down in our program past this until we know that both of those threads have completed their work and so in order to do that we just have to call the join method on both of them so t one dot join and t2.join so now both of our threads have completed their work they've both added a million items to our arraylist so now we need to capture the end time so we'll just go on up here and steal this and capture the end time just like we did before and then we'll also print out our results in a similar way but we'll say added elements in a multi-threaded way to arraylist and then we'll do the exact same thing but with a vector so let's go ahead and copy this whole section here paste it down below and all we're going to do is instead of multi-threaded list we're going to say it's a multi-threaded vector and instead of a new array list of course it's going to be a vector and then everywhere we have a multi-threaded list we have to change that to be multi-threaded Vector so there and there and change this to Vector in the output and and also since we've already declared these thread variables we don't need to declare them again here but we can reuse them all right so now let's go ahead and run this again and check out our results so similar results to what we were seeing before it did take a decent amount longer to add these elements in a multi-threaded way to Vector than it did to add them to arraylist let's give it a couple more runs and see what it does okay similar oh that's interesting so in this run we actually got an exception this was an array index out of bounds exception so that's kind of strange right why do we sometimes get an exception and sometimes we don't even worse though here's something that's even more Sinister let's check the actual sizes of both the multi-threaded vector and the multi-threaded list when they're done now of course we would expect them to both have 2 million elements in them every time because we have two threads that are both adding one million elements of piece but let's print out the size of each of them along with our results just to verify that so for the arraylist part we will print out size is multi-threaded list dot size copy that and so down here for the vector size is multi-threaded Vector dot size let's see what we see okay so now in this run our Vector does have exactly two million elements in it just what we would expect but the array list only has a little over 1.5 million elements in it pretty weird right let's run it again and see what else happens so here we got an exception again when it was trying to add to the arraylist and we only got just over 1 million elements in our arraylist and if we keep going we see similarly wacky unpredictable results each and every time so in this situation yes the arraylist performs its task faster but pretty much every time it's not actually getting all the 2 million elements that we would expect added to the arraylist but the vector even though it's taking a little bit more time it's always successfully adding all of the elements even with two threads running at the same time so the big question is why is that happening why do we get such unpredictable results when we tried to use an arraylist in a multi-threaded way well the reason is that operations on an arraylist are not synchronized that means they're not thread safe in other words having multiple threads trying to operate on an arraylist at the same time results in completely non-deterministic wacky Behavior but operations on vectors are synchronized so you can operate on vectors with multiple threads at the same time and not run into these kinds of weird exception situations so that of course can be useful if you're operating with multiple threads but that thread safety comes at a performance cost and if you're not using multiple threads vectors take all of that extra time for no real gain at all however here's a really cool thing let's say you still you don't know about vectors or you don't want to use them you just know about arraylists but you want to use an arraylist in a multi-threaded environment and not have this terrible wacky unpredictable behavior and there actually is something you can do to make your arraylist operations thread safe and it just takes one small change to your code so back up here where we're declaring our multi-threaded list instead of just saying new arraylist you just say collections dot synchronized list and then pass in your new arraylist as a parameter this creates a wrapper around your arraylist so now every time you're performing operations on your multi-threaded list they will all automatically be synchronized just like a vector does so now if we rerun this we can see that it is successfully now adding all 2 million items to the arraylist just exactly as the vector did if we go ahead and run that a few more times we can see this time the arraylist was just a little bit faster than the vector but pretty comparable here again almost exactly the same amount of time and running again performance is almost identical in a multi-threaded environment but now we have a nice arraylist that doesn't randomly explode in spectacular fashion when we do something as simple as trying to add elements into threads now where does that leave us what do we do with these vectors the general recommendation and this is what you'll probably hear if you Snoop around on stack Overflow or ask an experienced developer generally just use arraylist in the relatively rare circumstances that you need to synchronize those individual operations across a whole bunch of different threads you can just use this synchronized list wrapper to take care of that but the vast majority of the time you're just working with a single thread and so if you used a vector you would be sacrificing all that performance for no reason and even if you are using multiple threads it's pretty rare that you actually need to synchronize every little individual operation and it's more likely that you're synchronizing over a few operations like checking to see if something is in the list and then adding it or something like that and for that you'd have to write your own little synchronized method anyway but vectors are still around they've been in there since the very first version of java they're almost definitely not going anywhere anytime soon but for a modern developer they can mostly be seen as a relic of Java's past so you can take a tour through the Museum of java history and say oh vectors but just go ahead and keep using arraylists if you enjoyed this video or learned something please let me know by leaving a like and be sure to hit the Subscribe button so you don't miss each new video check out the course in the link down in the description if you're interested and as always thank you so much for watching I really appreciate you being here with me and I'll see you next time
Info
Channel: Coding with John
Views: 76,060
Rating: undefined out of 5
Keywords: java, codingwithjohn, coding with john, java beginner lesson, Java vectors, java vector, java vector class, java vector vs arraylist, java vector class methods, java vector example, java vector api, java vec, java tutorial for beginners, learn java, java tutorial, vector in java, collection framework in java, vector in java explained, vector in java learn coding, vector in java program, java tutorial for beginners in english
Id: s2h_lYgbkPI
Channel Id: undefined
Length: 16min 12sec (972 seconds)
Published: Mon May 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.