This question already has answers here:
Initial size for the ArrayList
(17 answers)
Closed 7 years ago.
How can I initialize the size of an ArrayList? The below code that works for initializing the size of a int array but does not work similarly for ArrayList. It prints 10 for the int array and 0 for the ArrayList. Thank you.
int[] intArray = new int[10];
ArrayList<Integer> arrlist = new ArrayList<Integer>(10);
System.out.println("int array size: " + intArray.length);
System.out.println("ArrayList size: " + arrlist.size());
That is because ArrayLists work differently than standard arrays.
When you pass in 10, you're telling it to allocate space for 10 elements, but since you haven't added anything to the ArrayList yet, size() will return 0.
Try adding an element and then printing the size - that should help you understand how it works. When in doubt, check the docs.
The size that you pass as argument is the initial container size for arraylist. Once you start storing database then only you will get appropriate size for your arraylist. Since the nature of the ArrayList is keep growing/reducing with the data insertion/removal into/from the list.
Related
This question already has answers here:
Initial size for the ArrayList
(17 answers)
ArrayList initial capacity and IndexOutOfBoundsException [duplicate]
(3 answers)
Closed 2 years ago.
ArrayList<String> Array=new ArrayList<>(5);
Array.add("Ten");
Array.add("Twenty");
Array.add(4,"Fifty");
Array.add("Thirty");
Array.add("Fourty");
System.out.println(Array);
I got the IndexOutOfBoundsException exception when I run this code. Can anyone explain the reason why I am getting this error?
I think this is caused by your misunderstanding of the first argument to the ArrayList constructor. It is not the initial size you are providing, but the capacity.
The ArrayList class works with both a size and capacity. The size is the actual number of added elements within the list. The capacity, however, is the size of the internal array of ArrayList where the actual elements are stored. If enough elements are added, the capacity is increased by copying all elements of the current internal array to a new array with double the size of the current one. This is done because otherwise you have to expand the internal array each time an element is added. That would seriously impact performance.
The single-argument constructor accepts the initial capacity, and not the size. It's common not to specify the capacity, because the capacity is initialized to a sensible default. This constructor, however, exists mainly for performance reasons: if it is known that the number of elements will become very large, one could set the capacity through that constructor, so the ArrayList does not have to resize a lot of times.
You are trying to add "Fifty" at index 4, which is not available because the size of ArrayList is 2 at that point of execution.
Array.add(4,"Fifty"); Adding "Fifty" at index 4
From the void java.util.ArrayList.add(int index, Object element) method declaration :
Throws: IndexOutOfBoundsException - if the index is out of range(index < 0 || index > size())
So you cant add to index number 4 because there is not one at the time the method is called
If you check out the docs, it clearly mentions that:
Throws:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
At the point of execution, your list size will be 2 and 4 > size i.e 2. Hence, this exception will be thrown.
You can check out the same discussion in Stack Overflow as well.
Your code declares the capacity of your ArrayList, not its actual size. So you can add elements, but adding to position 4 fails because that position doesn't yet exist.
You can check that by looking at the size of your array as you add elements:
System.out.println(array.size());
Adding a value increases your array's size by 1. But if your array's size is only 2, you'll get an error if you try adding a value to position 4.
Depending on your end goal, you could add a couple blank values in order to initialize those positions, then add to position 4:
ArrayList<String> array = new ArrayList<>(5);
Then you can do your adds:
array.add("Ten");
array.add("Twenty");
array.add("");
array.add("");
array.add(4,"Fifty");
array.add("Thirty");
array.add("Fourty");
System.out.println(array);
This question already has answers here:
Does the capacity of ArrayList decrease when we remove elements?
(7 answers)
Closed 3 years ago.
If you have an Array List that has been extended (the array has grown) to contain many elements and these elements are then removed, does the actual array size change to save memory?
In more details, when removing an element from a large Array List, is the reserved memory for the array empty part of the array recovered? It would seem logic that since we expanded the array we might need to use this space and so it will not be touched.
However if we have a really large array list and we only use the first 10 or so elements, will the compiler (or on run time) realize that all the extra space is being wasted and recover it? (Will the actual array size be decreased? (Copying the elements into a smaller array?))
You can call trimToSize() in order to replace the backing array of the ArrayList with a smaller array that matches the size of the list.
void java.util.ArrayList.trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance.
This question already has answers here:
Distinction between the capacity of an array list and the size of an array
(7 answers)
In Java 8, why is the default capacity of ArrayList now zero?
(6 answers)
Closed 5 years ago.
As per the Java API the default capacity for a java.util.ArrayList is 10.
public ArrayList()
Constructs an empty list with an initial capacity of ten.
I created a list without specifying the initial capacity as below and found that the initial capacity is 0 for the list.
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list50 = new ArrayList<String>(50);
list.add("1");
list50.add("2");
System.out.println(list.size());
I know i am making some silly mistake in interpretation, please correct me.
The initial capacity of a newly instantiated ArrayList is 0 - for performance reasons, an empty ArrayList uses a shared default array of size 0, so that if no new items are added to the list, you don't pay for allocating a new array that is never used.
Once the first item is added, the DEFAULT_CAPACITY (which is 10) is then used, i.e. the ArrayList creates a new array with size 10, which will then hold the first item (and has 9 additional, empty slots).
So I think you indeed used a slightly mistaken interpretation of the documentation.
The initial capacity is 0, and is then increased to 10 upon adding the first item, in order to avoid immediate reallocation for adding the next subsequent 9 items.
size and capacity are not the same...
every time you call add, ArrayList invoke ensureCapacityInternal, there you can find DEFAULT_CAPACITY which is 10 as you pointed....
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
so this statement
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
increase the capacity to 10 after the 1st insertion
This question already has answers here:
Java dynamic array sizes?
(19 answers)
Closed 8 years ago.
How may I define an array in Java. when I am not sure of the Arrays size.
I am doing it to avoid Null Pointers
int[] arr1 = new int[21];
int[] arr1 = {11,22,33};
These are of fixed length, i need to declare an Array where the items to be stored in it will be decided at run time?
You could use an ArrayList, which dynamically grows/shrinks according to how many elements you place/remove in it.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
if you are not sure just declare it like this:
int[] arr1;
but you must know its size when you initialise it later:
arr1 = int[20];
//or
arr1 = {1, 2, 3};
On the other hand this is the situation where you should use List (like ArrayList) since they resize dynamically.
EDIT:
List<Integer> list = new ArrayList<Integer>();
//adding
list.add(2);
more methods here: http://docs.oracle.com/javase/7/docs/api/java/util/List.html
"Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk."
ArrayList Tutorial
This question already has answers here:
How to add new elements to an array?
(19 answers)
How can I dynamically add items to a Java array?
(11 answers)
Closed 8 years ago.
I have an array, defined as below:
String[] letters = {"ab", "cd", "ef", "gh"};
How would I go about adding an item to this array?
1.Arrays are fixed in size
2.Before declaring an array we should know the size in advance.
3.We cannot add anything dynamically to an array once we declare its size.
I recommend you to go for collection framework like List or Set where you can increase the size dynamically
By using this type of array initialization you cannot simply add more elements.
String[] letters = {"ab", "cd", "ef", "gh"};
Could be paraphrased as:
String[] letters = new String[4];
letters[0] = "ab";
letters[1] = "cd";
letters[2] = "ef";
letters[3] = "gh";
So, your array's length is only 4.
To add more elements you should somehow copy you array to a bigger one and add elements there. Or just use ArrayList which does the hard work for you when capacity is exceeded.
Java arrays having static size. One you define the size of a array, it can't grow further dynamically.
Your letters array has a size of 4 element. So, you can't add more element to it.
Use ArrayList instead
List<String> letters = new ArrayList(); // Java 7 and upper versions
letters.add("ab");
letters.add("cd");
....// You can add more elements here
This is not possible without a workaround
like http://www.mkyong.com/java/java-append-values-into-an-object-array/
try ArrayList, List, Map, HashMap or something like this instead