I have one doubt regarding Array List in java.
I am creating a simple program for array, which is like this
now i need to write this program using Array List, however i started writing, but i was confused in between and could not go further. The codes which i wrote for this are-
NOW HOW SHOULD I GO AHEAD, i am thinking as if i have taken wrong assumption to write it in Array List format.
Don't you know how to use a loop? If there is any order to your array, always fill it with a loop. [Advanced alternative: use Java8 and find out how to fill an array with a Stream.]
And always use a loop to display the contents of the array (or a Stream).
As PS says, is anything going wrong with your program?
So...what should your program DO next? don't think about it in terms of java code, but tell us in English. "next it should ask the user to input their age" or "next it should play a song by Lady Gaga" or "next it should calculate mortgage payments".
We don't know what it should do next, so it is hard for us to help
VineetS Sharma wrote:I was confused with in myself. Actually i was looking, how does this array list works in comparison to regular arrays.
Well, an ArrayList (and it's specifically "ArrayList", not an "Array List" or an "array list"; you need to be very careful to be accurate when you're writing programs) is first and foremost a List (java.util.List); it just happens to be based on an array, so retrieving specific elements (eg, element #17) is very fast.
But don't get too hung up on the name. The designers could just as easily have called it "IndexedList", and you might never have made the connection with an array.
However, to answer your question: An ArrayList works rather like a "dynamic" array - which is to say that it will automatically increase in size to accommodate new elements; an array won't.
If you create a 'new String', it holds 10, and only 10, elements; you can't "make it bigger" (or smaller).
But if you create a 'new ArrayList<String>(10)', you can happily add 50 Strings to it, and the List will expand to hold them.
Hope that helps.
VineetS Sharma wrote:Thanks Fred,
I was confused with in myself. Actually i was looking, how does this array list works in comparison to regular arrays.
Now, I am able to execute it.
Being learner in Java, i got to know many things through these posts.
My initial reply was meant to draw your attention to two things:
1) you create an 'ArrayList<Int>',
Now, unless you have created a class 'Int', this will give you an error.
2) next, you try to put Strings in this list.
But I'm glad you solved all the problems. Indeed, there's a lot to know, but
foremost: there's a lot of information around, especially the Oracle API's!