Тёмный

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

Coding with John
Подписаться 333 тыс.
Просмотров 75 тыс.
50% 1

Vectors in Java - What they are and how to use them
☕ Complete Java course: codingwithjohn.thinkific.com/...
What are Vectors in Java? How do they work, and how are they different from ArrayLists? Why should you use one or the other?
We'll learn all about Vectors in Java, why you don't see them much, but one situation you might want to use them.
Learn or improve your Java by watching it being coded live!
Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
Let me know what else you'd like to see!
Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
00:00 What are Vectors?
01:35 Using Vectors, and Performance
06:11 Multithreading!
13:03 What about ArrayList?
14:34 What should you use?
📕 THE best book to learn Java, Effective Java by Joshua Bloch
amzn.to/36AfdUu
📕 One of my favorite programming books, Clean Code by Robert Martin
amzn.to/3GTPVhf
🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
www.audibletrial.com/johnclean...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Camera I use for recording:
amzn.to/3wlXcmR
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com/donate/?hosted...
☕Complete Java course:
codingwithjohn.thinkific.com/...
codingwithjohn.com

Опубликовано:

 

24 май 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 144   
@DanteMorius1
@DanteMorius1 Год назад
ArrayList: "I'm fast at adding elements!" John: "But you did not add of them in multithread call" ArrayList: "I said I'm fast, not correct"
@monishbiswas1966
@monishbiswas1966 Год назад
Well they realised that synchronising things by default was a bad design choice as A) there was a performance cost to synchronisation as it stops the JVM fro m doing certain optimisations, and users should not may the cost of hey are notneeding concurrent access. B) if concurrency was required, you would probably need to synchronise the calling code anyway, to allow read and modify ops to be atomic, so no point syncronsing the list operations. You can see this in stringBuilder vs StringBuffer
@user-tm1ju3pz9c
@user-tm1ju3pz9c Год назад
That makes sense.
@haltsmaul.
@haltsmaul. Год назад
By the way, you can add underscores to number literals to make them more readable: int size = 1_000_000;
@ManosSef
@ManosSef Год назад
I never knew that and it looks so weird lol
@v0xl
@v0xl Год назад
jusr like in rust and js
@xyvadimxy
@xyvadimxy Год назад
@@v0xl and python :)
@yankobzykant5579
@yankobzykant5579 Год назад
It works only with Java 11 and newer, but yeah you can.
@nuclear.prometheus
@nuclear.prometheus Год назад
You can do 1e6 too
@micleh
@micleh Год назад
I've been longing for you to publish a new video, and each time I'm fascinated by them regarding presentation technique, confidence and knowledge gain. This video - among all others you've produced - will be added to the "interesting video list" of my computer science class here in Germany. Thanks for making these kinds of videos.
@chpsilva
@chpsilva Год назад
I started working with Java back in 2001 and one of the first things I learned was Vectors were a big no-no, but nobody bothered to explain why. Many years later you showed us the reasons, so thanks!
@vyankateshodilwar
@vyankateshodilwar Год назад
Really love the way you demonstrated this in the minimalistic way
@zeeshannaqvi4091
@zeeshannaqvi4091 Год назад
Hi John I really appreciate the effort you put into explaining Java topics with such simplicity. The first video I watched was on Optionals and it finally made sense why they were introduced in the first place. Can you please make a video on Java Functional Interface, Consumer, Predicate and Supplier?
@rlasc84
@rlasc84 Год назад
Hi! Nice video. When I was working with JTable I always extending AbstractTableModel using ArrayList because I believed that the DefaultTableModel was deprecated for use Vectors. But Vectors are still around here as DefaulTableModel too. Thanks John and sorry for my english..
@siomarapantarotto
@siomarapantarotto Год назад
I ❤coding with you John! I coded with Vector and then migrated to ArrayList, I knew about thread safe, but only in theory. Your class was fantastic for me to understand how this works in practice. Congratulations.
@PauxloE
@PauxloE Год назад
For the benachmarking, I'd keep the `new Thread` part outside of the timing - just time from before the starts to after the joins.
@enfieldli9296
@enfieldli9296 Год назад
Finally a new video
@KT-tc9jr
@KT-tc9jr Год назад
I want to buy your course but I have been with Java for some time now. Thus, I would 100% be buying your Advanced Java course which includes advanced contents just like how you do it in this Channel.
@stephanieezat-panah7750
@stephanieezat-panah7750 Год назад
I used vectors in C++ for years. I had no idea that Java had vectors. I shall continue using ArrayLists, as you instructed us. Thank you, Coding With John. Awesome explanation and demonstration, as always.
@ayankhanra7910
@ayankhanra7910 Год назад
no way anyone goes emptyhanded from your videos ,there is always something to learn in deep.. thanks teacher.....
@codeZarathustra
@codeZarathustra Год назад
Wow! John I have not idea about this concept, but now is clear. Thank you.
@earomc
@earomc Год назад
I love your videos!!! Learned something again I didn't know!
@christopherreif3624
@christopherreif3624 Год назад
I’m really glad I found your channel, thank you for such quality content!
@itsolidude2353
@itsolidude2353 Год назад
Hey John, love your vids! Will you ever make a video on thread pooling and asynch. programming?
@abhishektiwarijr
@abhishektiwarijr 8 месяцев назад
Thanks a lot for all of your information to the point content man. It would be great to see videos on SOLID principles and Design Patterns from you.
@alfredochola5971
@alfredochola5971 Год назад
Thank you very much John. You do teach really well.
@casperes0912
@casperes0912 Год назад
Vector is thread-safe, ArrayList is not, but ArrayList is faster. You can wrap it in a synchronisedList to get thread safety on ArrayList. That's the video condensed. You're welcome
@chan-edidz
@chan-edidz 4 месяца назад
@RustysAdventures
@RustysAdventures Год назад
Such an interesting video. I've used Vector in C++ but never knew it existed in Java too. Your videos are always so educational
@soniablanche5672
@soniablanche5672 Год назад
C++ Vector = ArrayList in Java
@yuriytheone
@yuriytheone Год назад
The Power of C++ you can write any realization you need both threadsafe and none... With or without buffering and so on...
@gamerzero6085
@gamerzero6085 Год назад
@@yuriytheone Yeah you can do all of that in Java too. Your point?
@monishbiswas1966
@monishbiswas1966 Год назад
I think they modelled the early Java on C++, which is why they used the same names. However they made a design error in making vector synchronised as you pay a high cost to it being synchronised, and also most ops require synchronisation at a higher level. They could not fix the design errors without breaking backward compatibility, so they created ArrayList instead
@SUMITYADAV-cy9hf
@SUMITYADAV-cy9hf 2 месяца назад
hey John !!! amazing work requesting you to create a spring framework course as well .
@tarifhalabi
@tarifhalabi 8 месяцев назад
Very interesting video. I used Vectors way back in 1.2 or 1.3 but never bothered to find out how they are different than ArrayList. Thank you. Keep up the good work.
@SandileMnqayi
@SandileMnqayi 4 месяца назад
❤ your videos, thanks a mill. Please show up how you would create your own synchronized class.
@joshuatienda
@joshuatienda Год назад
Good to watch your videos!
@pranavmahajan4190
@pranavmahajan4190 Год назад
This is the best video I have seen on Vector. Thanks a lot
@Blazsejka
@Blazsejka Год назад
Awesome as always. I work as a Java dev but I still can find interesting and not-known topics in your videos.
@Soltryful
@Soltryful 11 месяцев назад
Hello John, always appreciate your clear and concise way of explaining difficult JAVA concepts, can you please talk about Dynamic proxies when you get a chance? Thanks
@zakariyaechmaili5647
@zakariyaechmaili5647 Год назад
i have never heard of vectors lol, now I feel like I have a much better understanding of them. thanks for explaining the concept in such a clear and engaging way, seriously you are the only education youtuber that i watch his contents not because i have to but i want to, so fun to watch and not boring at all ♥ unlike many educational youtubers, can't wait for the next video keep up the great work! ♥(we miss the smile)
@snesmocha
@snesmocha Год назад
Laughs in c++
@nicholaswhite7351
@nicholaswhite7351 Месяц назад
Very good job. Best wishes to John.
@erickgozan
@erickgozan 9 месяцев назад
I love your videos, you really explain very well, greetings from Mexico city.
@SuprousOxide
@SuprousOxide Год назад
With the vector both add and get methods are synchronized. You might have a case where you build a list once, and then want to READ from it from multiple threads. That should be safe with just the unsynchronized ArrayList, but to be safer you could wrap the list in an Collections.unmodifiableList. Then you won't need the overhead of synchronization on your get calls.
@shaunhorton5619
@shaunhorton5619 10 месяцев назад
I have a quick question regarding the performance difference between Vectors and Arraylists, or more specifically with the synchronizedlist, if you create the synched list wrapper for your arraylist, does it only take that performance hit and start behaving comparably to a Vector in a threaded environment, or does it slow down the ArrayList when accessing it in a single thread also?
@bobfarker4001
@bobfarker4001 Год назад
Im going to use start and end to measure my code's time. TY
@trup10ka
@trup10ka Год назад
Hello, awsome video as always, i learned so much from you. I wanted to ask if you could do a video about Http requests
@gowthamselvaraj7793
@gowthamselvaraj7793 8 месяцев назад
Thats a very good explaination. ArrayList has less time for execution but vector is high and Threads are high in Vector but less in ArrayList.
@andromilk2634
@andromilk2634 Год назад
Please, do more videos, I love them.
@anpadjahil9711
@anpadjahil9711 Год назад
Thanks a lot John.
@re37re
@re37re Год назад
Hi, John! Can you make a video on Quarkus and GraalVM?
@user-hw1tw8qu8y
@user-hw1tw8qu8y 11 месяцев назад
SIRRRRRR......U R Great... you solved my longlasting issue by vector class. i was making a 2d style java game and usling LinkedList. when i skip level or in fast or sometime it stuck it always gave me error. linkedlist. it tried above code for sync, but did not work. after watching your video, i changed it to vector . no issue now, no significant or noticable lagg or any issue that was facing and hitting head with codes and its technique OOP method. Great.......
@svalyavasvalyava9867
@svalyavasvalyava9867 Год назад
awesome video, thank you! 😊
@fahadgaliwango4502
@fahadgaliwango4502 3 месяца назад
Thanks for sharing about vectors asd arraylist , you demonstrated how arrayList performs poorly with multi threads if not synchronised. what happens if parallelStreams are used? Does it automatically gets wrapped into Collections.synchronized()
@paulushcgcj
@paulushcgcj Год назад
Great video. One suggestion I would give is to use Duration to measure time instead of System.currentTimeMillis() as it is not that reliable, specially when dealing with lots of data, the effect of CPU throttling and time leap will mess your count. LocalDateTime with duration to measure the difference is better
@kc7718
@kc7718 3 месяца назад
Vectors is one of the topic that always kind of confused me. Thanks for detail explanation
@sohpol
@sohpol Год назад
Me Gusta :) Next video, maybe something about switch statement and how it evolved in Java? Or maybe something about using debugger in most popular IDE's? That would be also extremely useful for beginners :)
@GeoffryAbiFarah
@GeoffryAbiFarah Год назад
Great video!
@sirinath
@sirinath Год назад
You can used synchronized in one of the threads. This synchronises in both threads which might not be necessary when there are 2 threads. N threads N - 1 synchronisations. If N is large you can synchronize all threads.
@chrisp267
@chrisp267 Год назад
Good video! One question: Aren't Vectors deprecated?
@mihirgore4074
@mihirgore4074 Год назад
After so long....good to see it :)
@madhav_0075
@madhav_0075 Год назад
Sir kindly create complete video for Java . Which will be helpful for lot of beginners to understand what exactly java❤
@brenolavieri
@brenolavieri 9 месяцев назад
OMG - im suffering here with vectors for no reason at all...Thx for this excellent explanation
@michaeltaylor4817
@michaeltaylor4817 Год назад
no idea if it has been covered, but explaining public, private, protected and package private might be a good idea. just a thought. and in my opinion making some examples a little bit more complex might help for like a real world example. as extending some functionality might be tricky for learning developers. also if possible, please stick to one IDE swapping between intelli J and Eclipse can be mildly distracting. and an ide specific functionality is a pain if someone is using Eclipse and they wanna do something only available in Intelli J other wise love your good work, very helpful could we have a lesson on FUNCTIONS, BIFUNCTIONS, SUPPLIERS, CONSUMERS and other functional interfaces with a demo of passing them to methods etc :)
@troeteimarsch
@troeteimarsch Год назад
perfectly informative :)
@ahmadiyad2860
@ahmadiyad2860 Год назад
thank you man
@fez0062
@fez0062 Год назад
Hello John! Please post more videos!! When I watch your explanations I don’t feel like a complete idiot who can never be a developer but the opposite!!!! It would be cool if you made some videos about patterns of programming or about spring framework or about microservises Anyway whatever you do I love your content!)
@anath04
@anath04 Год назад
Could you please make some video on Reactive Java , particularly project reactor.
@timkreutzkamp8519
@timkreutzkamp8519 Месяц назад
Funny Thing is if i switch the first example around, adding to the vector is faster than adding to the arraylist. Checked again with two ArrayLists and adding to the first datatype is always half the time than adding to the second one ^^
@saddyman__7107
@saddyman__7107 Год назад
Hi, Can you make a video about composition ? thx a lot
@MuksEmmaN
@MuksEmmaN Год назад
Hi sir can you please do a video on Thread pools and executor service in Java?
@mminahid9662
@mminahid9662 9 месяцев назад
in javaFX Application is an abstract class. In this abstract class there have some abstract methods which are overridden in main class which extends abstract Application class and also have static launch() method in abstract class Application. The launch() method calls from the main method in main class. Now how is it possible launch() method calls these abstract methods and for these calls overridden methods in main class are executes? please help to understand
@jansentanu2637
@jansentanu2637 Год назад
What's the font you use in the code editor?
@ALORCARD
@ALORCARD Год назад
I never see join() method, it's possible to make deadlock with it?
@mayurlaniya5049
@mayurlaniya5049 Год назад
awesome!!! JOHN
@yuriytheone
@yuriytheone Год назад
Hello and thank you. Should we use Vector if we are just reading from List in multithreading mode? Is ArrayList is safe for reading in multithreading? Thanks in advance!
@monishbiswas1966
@monishbiswas1966 Год назад
If it’s only accessed from one thread you do not need to synchronise, and if it’s accessed from multiple threads you may want to handle the synchronisation in the surrounding code to allow several operations to be atomic. Alternatively there says there are constructs that are better suited to concurrency, such as a concurrent hash map
@yuriytheone
@yuriytheone Год назад
​@@monishbiswas1966 thank you for reply
@exitspree
@exitspree 11 месяцев назад
The way you explain things is so nice.
@WiseDog1
@WiseDog1 Год назад
hello John, love your content. Can you make your course available on Udemy or LinkedIn ?
@anaselmakhloufi2180
@anaselmakhloufi2180 Год назад
ArrayList is fast because it is non-synchronized , Vector is slow because it is synchronized
@neelkrishna
@neelkrishna 5 месяцев назад
I'm running this code locally and the elements are being added to a vector about 2x faster than an arrayList (consistently). Could this be because I'm on an M series Mac with ARM architecture?
@B.Aboobaker
@B.Aboobaker Год назад
can you please make a video on: encapsulation, inheritance, polymorphism, and abstraction... pleaseeeee
@sagniksaha4179
@sagniksaha4179 Год назад
That was damn good info
@oguzhantopaloglu9442
@oguzhantopaloglu9442 Год назад
Whole video summarized in a sentence: Vectors are slower because unlike arraylists they are thread-safe so just use arraylists and if you have multiple threads use Collections.synchronizedList(arrayList).
@codingoak4701
@codingoak4701 Год назад
This is perfect
@clingyking2774
@clingyking2774 Год назад
Someone tell John we would really love an intro to springboot course from him, perhaps some 30 min crud app of some sorts. His videos helped me finally get the hang of recursion after reading hundreds of articles and numerous youtube videos later.
@CodingWithJohn
@CodingWithJohn Год назад
I'll let him know 😮
@clingyking2774
@clingyking2774 Год назад
@@CodingWithJohn Lots of thanks.
@user-kr8uu3bm4k
@user-kr8uu3bm4k Год назад
Hello , John Ukraine is watching you 🇺🇦 You are the best Java-blogger I’ve ever seen)
@redcrafterlppa303
@redcrafterlppa303 Год назад
When using awt/swing parts of the api uses vector (probably because the api was written before the collections framework) and it's pretty annoying to be forced to use vectors in multiple places or copy a bunch of array lists into vectors.
@awesomebearaudiobooks
@awesomebearaudiobooks Год назад
Can someone please explain, why do I get the same results for both ArrayList and Vector? I am not using any wrappers, I am jsut running the same code as John, and yet my ArrayLists are not in any way faster than my Vectors, why is that? Am I using a wrong JRE or something? Maybe there is something to do with Maven? For example, I get this: Added 10000000 elements to ArrayList: 251ms Added 10000000 elements to Vector: 242ms Added 10000000 elements in a multithreaded way to ArrayList: 1030ms Added 10000000 elements in a multithreaded way to Vector: 1275ms
@ramosm198
@ramosm198 Год назад
hahahaha the end was awsome, thanks man u r the best
@fexofenadinaGenerica
@fexofenadinaGenerica Год назад
Cool content
@Zeero3846
@Zeero3846 Год назад
Vectors in Java were initially implemented to be thread safe as the original philosophy in Java was to just do everything one way to fit every use case. It's the reason why every method is virtual and must be contained in a class, among other things. By the way, the other data structure from the original Java version is Hashtable. It corresponds to the more useful HashMap. It's also worth noting that Java also have a number of other concurrent data structures in the java.util.concurrent package, like BlockingDeque, ConcurrentHashMap, etc.
@techStatuss
@techStatuss Год назад
What about concurrent collection?
@jacobmockler
@jacobmockler Год назад
Good Monday coffee waiting for breakpoints to trigger
@mauricesmith8234
@mauricesmith8234 Год назад
HEES BACK!!!!!!
@aaf2011
@aaf2011 Год назад
Hello John I would like to see a real practical example of using the java collection framework. I never understood the fundamentals of collection framework and if it is related to the database like mysql. I am really struggling with the concept of database and data structures. Please help 😢 SOS
@sivakumar.s2559
@sivakumar.s2559 Год назад
Can you make a multi-threading video like one thread need to create a image in dir with distinct name and another side the thread need to write a text in one file upto 2 Million in efficient way
@VuLinhAssassin
@VuLinhAssassin Год назад
Is this Vector the same as something something Vector API coming with the most recent Java version?
@falklumo
@falklumo 6 месяцев назад
No, new vector api is about using SIMD processor instructions in a portable way.
@heyimemad5626
@heyimemad5626 Год назад
can u explain JavaFX Basics? please
@Gandobilis
@Gandobilis Год назад
❤❤❤
@cuongnguyenhuu2836
@cuongnguyenhuu2836 Год назад
why Arraylist is faster even in the single-threaded example?
@EnderCrypt
@EnderCrypt Год назад
Now compare vector and synchronized list (from Collections.)
@Jhonfreddy15
@Jhonfreddy15 Год назад
I think there is a new Vector implementation in the coming JDK, I thought this video was about that new feature 😅😢
@CodingWithJohn
@CodingWithJohn Год назад
I'll have to check into that!
@Zeero3846
@Zeero3846 Год назад
The only other situation is if you're using 3rd party code, and they force you to use Vector. Of course, you'd try to limit the use of Vector by copying into a Vector at the very last minute just before passing it as a parameter. If a Vector is returned, it may be useful to just put it into a List variable if you're not going to manipulate the elements in any way afterwards. If you are, still put it in a List variable, but consider if you need the thread safety. If not, then copy from the Vector into an ArrayList.
@Qbe_Root
@Qbe_Root Год назад
could've extracted the single-threaded and multi-threaded benchmarks into separate functions taking a List instead of copy-pasting and renaming variables all over the place
@jurgenaddicks1634
@jurgenaddicks1634 Год назад
But, I love my good old Vectors 😢, just kidding ! Nice Video 😀👍
@hansudowolfrahm4856
@hansudowolfrahm4856 Месяц назад
Haters gonna say the new updates are bad, but you can still use the old ones and also if you don't develop you will just get stuck in the past. I think most new things are optional and you don't have to use them, however it's always good to use both. I will continue to use the old hello world but I will also try out new things and learn the new update as well. Having additional knowlege will always give an advantage.
@PauxloE
@PauxloE Год назад
One other difference: If you don't use the List interface, Vector has a lot of additional methods which are just confusing.
@baibula
@baibula Год назад
You should use CopyOnWriteArrayList, not Vector.
@LourenzoFerreira
@LourenzoFerreira 7 месяцев назад
I saw weird behaviours when testing... I ran it with Java 20, and consistently Vector was faster than ArrayList with a milion item, but with 10, ArrayList is faster again...
@devoiddude
@devoiddude Год назад
I did not know vectors existed in Java, I thought they were just in C++ and C.
@pneuma1387
@pneuma1387 Год назад
Hey, I think to get more accurate results you should call garbage collection after each benchmark.
@leeamraa
@leeamraa Год назад
where is the source code of this video?!
Далее
Lambda Expressions in Java - Full Simple Tutorial
13:05
Hidden Beauties of Java Enums
22:20
Просмотров 9 тыс.
Set and HashSet in Java - Full Tutorial
20:43
Просмотров 189 тыс.
Generics In Java - Full Simple Tutorial
17:34
Просмотров 1 млн
Vim as your editor - Advanced Motions P2
12:48
Просмотров 162 тыс.
Dynamic Arrays in C
11:46
Просмотров 62 тыс.