Array vs. ArrayList in Java Tutorial - What's The Difference?
HTML-код
- Опубликовано: 30 сен 2024
- Arrays vs. ArrayLists - What's the difference? How do you use each of them, and which one should you use and why?
We'll go in-depth about the similarities and differences between Array and ArrayList in Java, and talk about how to create them, add elements, remove elements, and more.
This is a beginner friendly beginner's Java coding lesson tutorial, where we'll talk all about using Arrays and ArrayLists.
Learn or improve your Java by watching it being coded live!
Hey, I'm John! I'm a Lead Java Software Engineer who has been in the industry for over a decade. I love sharing what I've learned over the years in a way that's understandable.
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.
📕 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.audibletria...
🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
bit.ly/3QPNGko
📹Phone I use for recording:
amzn.to/3HepYJu
🎙️Microphone I use (classy, I know):
amzn.to/3AYGdbz
Donate with PayPal (Thank you so much!)
www.paypal.com...
☕Complete Java course:
codingwithjohn...
codingwithjohn...
Full source code available here: codingwithjohn...
Easily top 3 programming teachers on youtube. No joke. You seem to answer the exact questions that a newbie would asks and you answer in such a way that gives exactly the information that is needed.
who is rest?
@@ilhammammadli4560 Corey Schafer is one of them for sure.
Agreed! I´m a first semester Computer Science student and we must do these little coding exercises. The lectures don´t really help, but these videos really got me through these tasks.
This dude is the man. His videos are better than others because he answers the question why. Why do we do it this way? Keep it up dude.
It's well explained, unfortunately underated you should have more than a million subs. By the way I subbed and will make you a step closer to million😍😍
I know this video is old, but thank you so much John!
Please make more videos. I really like your teaching style. Thanks...
super explained, with respect from Germany🙏
I’ve been using Collection Lists for so long, I forgot that the Java Array was fixed size! 😂 Thanks for the reminder.
Very well explained , Thank you John.
Love from India 🫀
For people wondering how, you can print out an array. Here is the answer:
for (int[] x : matrix){
for (int y : x){
System.out.print(y + " ");
}
System.out.println();
}
(If you do it like this, the array will look like a matrix)
Great video, as usual. Thanx!
PLEASE DONT STOP TEACHING THIS THINGS.. I HAVE WATCHED A LOT OF GUYS LIKE U ON RUclips AND UR ONE OF THE BEST. AND STILL I LOVE JAVA MORE EVEN AFTER MEETING PYTHON
i can relate to that❤😎👌
I didn't see the DONT and I got really confused
Caps Lock. The cruise control to cool 😎
Axper angleren chem xosum ches kara bacatres incha patmum?
@@spacepowerofficial1187 PLEASE STOP TEACHING
imagine
you are going to have million subscribers one day, already telling ya, you teach so well :)
I Second that
That's a nice notion but no he wont. Programming is not that popular. Only stupid things are popular, entertainment and food and monkeying around
I agree... he is great teacher, I love his coding tutorials cuz they are the ones that are among the most understandable and well-explained:)
indeed
He is close
You explain diamond operators (starting at 4:19) in 20 seconds better than others who have taken over 5 minutes. Well done sir.
Johnny Sins is really a great java teacher
Great video. Two things....it's considered good practice to use the interface on the left side so List instead of ArrayList before the variable name. And while you are right that the ArrayList itself can grow and shrink it's really important to be aware that the array that backs the ArrayList (yes there's an array hiding inside the ArrayList implementation!) does not shrink automatically after the ArrayList has grown...this can be very significant when profiling the memory footprint of an application. Lastly, it would be really good to have a video on why you'd pick a primitive representation over its Object form.....performance, memory usage, etc.
Thanks so much for sharing this video! We watched this in my AP CS A course after finishing a unit on Arrays and you did a great job of giving us an intro to ArrayLists.
I was not expecting such a easy to understand, and great tutorial like this! thank you so much
RUclips algo sucks for not recommending this wonderful video for Java learner! But better late than never!
Its mind blowing how your channel has so few subscribers....
I feel like Arrays are like the first born dumb child and after that, the parents decided "you know what honey, I think we should give it another go 🤣. And the ArrayList was born.
Underrated Comment
as I was watching I thought "BUT-BUT you cant DO THAT!" and then you wrote "//you can't do that "
and i got just a nice ass dopamine hit, thank you.
I freaking love the way you approach the subject on your videos... It's so simple and yet, complete; I can understand everything so easily.
Damn bro, you damn it down so badly! thanks bro.
your channel is about to explode
can u make video for 2d array list how to insert ,access and store in another variable??
sir, just want to let you know that you are f***king awesome!
I just noticed that sweet Kramer portrait behind you Haha
Thanks for the help! Java is an interesting language so far, and this definitely helped me see things a bit better.
Cool video. So informative yet so clear and easy to understand. I’m learning java programming as a hobby language and your explanation is the best I have seen on RUclips!!!
Thanks dude, you make everything so simple!
Thanks for the video, can we do this @6:37 ArrayList friends ArrayList2=new ArrayList(Arrays.asList(friendsArray2)); and still keep it as Mutable??
Yep I think that would make a mutable friendsArrayList2 also.
I didn't go into this in the video, but if you declare it as a List instead of an ArrayList, you can make it even simpler and also have a mutable list:
List friendsArrayList2 = Arrays.asList(friendsArray2);
This gives you the same result, but it was confusing in a short video to go into why you could declare a List and initialize it as an ArrayList. (Hint - it has to do with List being an interface, and ArrayList being an implementation of that List interface)
you are 100% my go to person on RUclips for beginner tutorials -> explanations are always really beginner friendly and so clear and easily digestible. Thanks a ton man
Quick question is arraylist a class? I think based on this yes.
Correct, it's a class. docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
I love how my school explains these things in 10 videos and it takes over 5 hours to watch all of them, while I can easily learn it from your video in just 18 min
If you had 2 elements in an arraylist both with the value "john", would a .remove("john") remove both or just the first one?
I think when he finds the String "john" first it will only remove the first one
Shariq is correct, .remove() just removes the first one. There's also a .removeAll() method available to remove all of them.
You can find all that info on the official documentation here: docs.oracle.com/javase/8/docs/api/java/util/List.html
The documentation is always a great source for finding exactly what a method does. You should also be able to see those javadocs in your IDE, usually just by hovering your cursor over the method name.
I am studying from Udemy but I got confused because of the way the tutor explains. However, man you clear those confusions. Thanks man.
The performance difference does add up if you’re using a ton of arrays in your code, or if you’re iterating a lot over the same array(s). With ArraysList Java has to do dynamic allocation behind the scenes, meaning it has to allocate new memory AND copy all the elements from the previous array list whenever you want to resize to a new larger array list. It can definitely slow down your code if you have lots of these lying around or if you’re iterating a lot.
Could you specify out of both of them which were to be faster if used non iteratively many times or even if one of them is to be faster how much of a time difference would it make?
English is not even my first language but I understood most of the things you said, this is pretty helpful, you will be big one day
your vids and dedication should be worth more than 2.05M subs not 2.05K subs. Thanks for vid. your vids really help me out! :)
thanks for making such an awesome lecture. hoping for more such tutorials
I am literally I am shocked how come you do not have 1 million subscribes ..the way you teach is awsome.
What if when creating a array , I specify the size with a variable and then increment it later, will now be able to add more values ?
Eg:
int h= 10;
int[] arr= new int[h];
h+=1;
arr[10]=12;
The statement
int[] arr = new int[h];
acts like
int[] arr = new int[10];
@@sianke1991 thank you ❤️
Just like Python has a Sentdex, Java has a John 💞💞 You guys are awesome!
Watching your videos helps me understand so much better. You explain everything perfectly and add in the little important details that most books or instructors seem to not mention,
Thank you!
Any advantage in using one of these over the other?
List myList = new ArrayList();
ArrayList myList = new ArrayList();
Someone asked a similar question in my polymorphism video, and I gave a long answer that I hope is helpful. I'll paste both the question and answer here.
I'm struggling with the instantiation of the subclass. Well, it happens that the way I learned to do my instantiations is as it follows:
SubClass object = new SubClass();
But some people do it differently, and that is the way that it is represented in the official Java documentation about Polymorphism:
SuperClass object = new SubClass();
And I can't figure out why is this even a possibility, because when you instantiate objects with the second way, you can't access the SubClass methods (unless they are overrided methods and have the same name in both classes).
Could you explain this to me? Because I noticed that in the video you did the instantiation the same way as I do. Thanks in advance.
Great question! You can certainly do both, and using the superclass as the type has the limitations you noted.
Most of the time, you're just fine using the SubClass as the type, as you describe how you usually do it. However, there are situations where it makes sense to use the superclass, such as specifically when there is a polymorphic method like you noted.
Let's say you had an Instrument super class, and a bunch of sub classes of Instrument like Guitar, Trombone, Drum, etc.
Your Instrument class could have a play() method that makes a sound, and all subclasses would override that method with their own implementation.
You could write a method that looks like this:
void playSound (Instrument instrument){
System.out.println("Playing my sound: " + instrument.play());
}
This method doesn't know and doesn't care what type of instrument is passed in - it just needs it to be an Instrument, so that it knows it can call its play() method.
If you want to use that playSound() method in that kind of situation, you have to create your instrument like:
Instrument drum = new Drum();
playSound(drum);
When working with collections, you'll probably run into similar situations, just with Interfaces instead of superclasses.
For example, ArrayList is an implementation of the List interface. So usually when declaring an ArrayList, you should do this:
List names = new ArrayList();
This list happens to use an ArrayList as its underlying implementation, but any method that takes a List of Strings doesn't care whether you use an ArrayList, or LinkedList, or whatever. Then you can have a method like this:
void printNames (List nameList) {
...
}
Similar to the playSound() method above, this method doesn't care whether you used an ArrayList or some other kind of List implementation - it just needs to know it's some kind of List to do what it has to do. And the user of the method can use whatever type of List they want to use for their particular situation.
That's a very long answer, but hope it helps clarify it a bit!
@@CodingWithJohn Thanks! 😊
This is amazing.The explanation is really easy to follow and understand. I hope many more people can watch and subscribe. Thanks for the tutorial
Thank you John for simplifying the subject of Array & ArrayList, please consider doing tutorials with IntelliJ IDEA CE, much appreciated!
My Exam is on Monday and my teacher did not cover this topic on JAVA. By watching this video I'm prepared for my Exam, thanks very much.
i love all your videos! it helps a lot and explained very well.. please keep on making videos about java..
Just searched for a good video and wow I could not have found a better one. Thanks a lot.
Wow. I compare you with my Java Prof at Uni Rheinland, Germany. He thought he was cool, but it took me long, to get the Java basics, while listening to his lectures. Your teaching method is amazingly more efficient in contrast to his. I am slow in my comprehension, not very intelligent, but within 15 minutes, you were able to help me resolving an issue revolving about some ArrayList-storage of Long Integers in the lower scale of billions of iterations and the numerical output in the order of a quadrillion (found some java JVM memory issues here). My bad programming :(
I applaud your generous input into our Java community.
You shouldn't lie to people about printing arrays. It makes biased and lacking in credibility.
You literally said that ArrayList implements the Arrays.toString() method. Meaning that if you use Arrays.toString on your array, it will print just like the ArrayList. I thought you were trying to educate, not spread bias over such an arbitrary topic to be biased over.
You are a breath of fresh air in a sea of crappy accents 😢. You are spreading dukes gospel, thank you John. Keep on keeping on ❤
Big O notation - Array List With Animated Examples for Faster Learning and Deeper Understanding # 1
ruclips.net/video/q0A8mZoj6ww/видео.html
Why can't you delete an element in Arrays by replacing it with null?
Чтобы распечатать массив не обязательно использовать цикл fori можно использовать метод Arrays.toString(ваш массив)
With so much gratitude I want to appreciate Dr ekpe on RUclips for showing up in my life at the right time. I have been down with HSV for almost a year, coming across Dr ekpe RUclips channel and purchasing his medication was the best news of my life. Thank you doctor
Great video, love your thorough way of approaching each topic! 👍
One question I find interesting is: Creating generic arrays (e.g. Stack[] genericStackArray = new Stack[10]; ) is not allowed -- the compile-error is simply "generic array creation". On the other hand if you use an ArrayList (e.g. ArrayList genericStackArrayList = new ArrayList(); ) Java has no problem with the input type of the ArrayList being generic although the implementation of ArrayList internally uses an array. Do you have an explanation for that?
try this to make it more intresting List[] list = new Stack[10];
@KuenskeProductions
This is because type arguments aka generic type parameters, in Java, don't really exist at runtime. This is called type erasure.
Java arrays are supposed to encode information about its declared containing type. However, since generics don't exist at runtime, they can't be type checked at runtime and thus will lead to unexpected results.
Like in your example, the real type of the array at runtime will be just Stack[] (no generics). Instead of letting the generic type be dropped on the floor silently, the Java language designers decided to make it explicit that the generic argument can't be given because it would be dropped. Instead you must cast it manually to a generic type to acknowledge the limitation, and assert you can deal with it.
I can give code examples on request of the type safety horrors that would be unleashed if generic array constructor syntax would have been allowed.
@@leninkumarkoppoju7145 Unless your hypothetical Stack type is a List, Java would have been able to catch this type of misuse.
You can't assign an X[] to Y[] unless X is a subtype of Y. (Assume X and Y are actual types, not generic types) With manual casting, you can also do it if X is a super type of Y.
If they are not related by a parent-child relationship, then there is no way they could be compatible and thus the Java compiler rejects it as type unsafe.
For the pedantic among you, yes I know there is actually one thing about generics that does survive compilation. Type bounds in signatures/class definitions.
So if you declare
class StringPrefixTrieSet implements Set
then you would be able at runtime see from StringPrefixTrieSet.class (the Class object representing this class), through some messy reflection API to wade through, that it implements not just Set, but Set, or some subtype of CharSequence.
It is per instance of a class or per call of a function generic information that gets lost.
StringPrefixTrieSet true = new StringPrefixTrieSet(); // the String part vanishes entirely after compilation
In C#, they have the List and say it is "array-based". Is that the same exact thing as ArrayLists in Java?
John, I discovered you yesterday and you are one of the best!
Hello John. Your videos have always been very helpful. Could you make a playlist explaining Java Collections and all sorts of Map completely?
Really enjoying your videos!!! Keep it up!! Thank you!!!!
Nice video John, but with one little flaw. You don't need to write a loop to print an array.
String[] names = {"Amy", "Naomi", "Lovina"};
System.out.println(Arrays.toString(names));
I'm working on an adaptation of 2 REST API I did on Node with MongoDB to Spring Boot with MySQL. But every once in a while it's great go back to the hows and whys of Java. 👏👏👏
Nice to see you are using Eclipse. For some weird reason everyone around me in the corporate environment seems to prefer IntelliJ. I have been using eclipse since the first version. And Visual Age for Java before that. I feel so out of place.
ArrayList can grow or shrink and you can output the contents to display with a simple println() call. Case closed. Oh, and being able to create a stream with ArrayList, what more could we ask for?
God programing is confusing why doesn't giving your array size 4 as in
String[] friendsArray = new String[4];
mean that that there are 5 elements. What happened to 0? Like 0,1,2,3,4?
Sorry but at first I thought " what Johnny Sins also teaches java !!!?!?!?" Same look, same voice different profession.
Hi, John.
I had recently joined an ICT institute.
Please I kindly need your help with Java and the basics of the program that I can start with.
Please your advice will highly be helpful to me.
Thanks in anticipation.
Wondering if Groovy makes a distinction between these and its basic LIST structure.
John, I'm just getting started in Java and I appreciate you. Commenting to help the algorithm.
Great explanation! I’m from Brazil and your speeching is very understandable. Success in your channel
One way to print an array is to use this method:
System.out.println(java.util.Arrays.toString(arr));
Quality content, great at teaching, quality video and the most important for me is that as a non native English speaker I can perfectly understand everything you're saying. This channel deserves at least 1 million subscribers and hundreds of thousands views. Keep it up, man. 🥂
Hope your channel grows that much, that all the subscribers don't fit in an ArrayList...Subscribed!
So, I woke up 4am, and feel like should get up and program. Thank You Mr. John, God bring me here I guess
You are really superman.. Because your video helpful to everyone... I saw a video from tamilnadu in south India....... Your are my best teacher
Is there a difference between :
ArrayList mc = new ArrayList()
And
List mc = new ArrayList()?
Thanks John. This is a great learning. I would recommend this channel to my friends too because things explained are to the point, no random things. Thanks again. Subscribed
Hey, John.
Can you do one like this on String vs StringBuilder?
There isn't a lot on StringBuilder in the RUclipsverse...
You explained the difference real well, but I find the advice unusual
Use what is most suitable for the task, not "ArrayList because it is more capable"
Yoo i was thinking that SingleLinkedList and ArrayList is same thing, and i was confused. Thank you brother.
You would be an amazing CS professor, thank you for saving my degree 🙏
This was really good!
2 questions I had I already figured out by now so I deleted them.
Don't worry Chris is Died and he always FORGIVE ❤❤ TWD❤❤
love from India bro....u know exactly how to teach....just amazing
Thanks, you're a great teacher!! It's incredible how you can make it so easy to understand
Do you have content that goes through how Java resizes ArrayLists? how about the space and time complexity of the inserts and deletes?
Hi John. Thank you for these teachings. I really appreciate it.
If I may ask... Can you think of a case one would have to use an array.
I liked that CARL thing with Picture 😂 carl from The walking dead
Hello, first of all I would like to thank you. I have hard time to write sysout. Carl+ space. Either anyway to write it? Thanks.
I thought you might give me a reason why should use Array...
A little bit guilty about using ArrayList only because it's too easy...
Sorry Array...
Thank you for ur content! But one thing, you say that, if we declare an ArrayList with the Method arrays.aslist() it makes the list immutable. But if i try it out, I can still add elemts into the list. Can anyone expain what i did wrong?
What is the point of using Arrays then? You can use arrayList instead. The difference is explained really well thank you.
It blew my mind when I learned that you can resize an array by making a copy of it with Arrays.copyOf().
Worked great for a solution where I needed to break an input string into parts, but some of the parts ended early.
If the scanner.nextLine() only made a String array of length 2, copyOf and resize it to 3!
Thank you John for simplifying the subject of Array & ArrayList, please consider doing tutorials with IntelliJ IDEA CE, much appreciated!
Hi, can you go over streams? i kind of understand them, but i always forget how to use them bc i don’t understand them fully
Liked & Subscribed. Thank you for the wonderful explanation.
Ew Eclipse. Why'd you ever use anything else than IntelliJ for Java...
Very clear and detail, it really helps a lot! Will subscribe and hope to see more videos soon!
Mr.John, passing the code you wrote in the first comment could be a great way to make hands dirty!