Instantiating an ArrayList of ArrayLists - java

I want to instantiate an ArrayList of ArrayLists (of a generic type). I have this code:
private ArrayList<ArrayList<GameObject>> toDoFlags;
toDoFlags = new ArrayList<ArrayList<GameObject>>(2);
Am I doing this right? It compiles, but when I look at the ArrayList, it has a size of 0.

You're doing it right. The reason it has zero length is because you haven't added anything to it yet.
The "2" you pass is the initial capacity of the array that backs the ArrayList. But the size() method of the ArrayList doesn't return the initial capacity of its backing array... it returns the number of actual elements in the list.
Customarily, you shouldn't be using the initialCapacity parameter. It's a performance optimization when you have large ArrayLists. By allocating a lot of space explicitly, you save the time it would take to re-allocate as you add more and more items to the list. But in this case you probably don't have an extremely large list.
Also, instead of using an ArrayList of ArrayLists, you should consider writing a class to store your data.

ArrayLists expand as you add to them. The integer capacity argument just sets the initial size of the backing array. Setting the capacity to two doesn't mean that there are two elements in the ArrayList, but rather that two elements can be added to the ArrayList before it has to declare a larger internal array.

Related

How to enter values in arraylist without asking the size of the array?

I want to give input 4,5,6 to the arraylist then next time i want to enter 83,2,4,5 without asking the size of the array from the user,using the scanner class.The input would be given at the run time.How could it be done with the help of arraylist.Is there any other way to do it?
this may help:
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index basis.
In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Basic exsample:
ArrayList<Integer> collection=new ArrayList<Integer>();
collection.add(83);
collection.add(2);
collection.add(4);
collection.add(5);
OR dynamically
boolean endContition=false;
while (!endContition){
int element= readElement(); /*retrive element to add in some way*/
collection.add(element);
updateEndContition(); /*if someting happens swich endcondition*/
}
but pls try to be more specific when u ask!
Consider the following:
When the user is entering his input line, create a new ArrayList()
Lets say List list = new ArrayList();
Now, for each item in the input call list.add(/* user input here */);

Initial capacity for CopyOnWriteArrayList

Many List implementations have an option to specify an initial capacity for the collection, why is this not allowed for CopyOnWriteArrayList?
In a conventional ArrayList the capacity is a hint to reserve more space in the backing array for more elements to be added to the list later on.
In a CopyOnWriteArrayList, every (atomic) write operation creates a new backing array. There is no point in preallocating an array that is bigger than the current list size because that space would never be used.

How does Java implement "growable array" internally? [duplicate]

What data structure does an ArrayList use internally?
Internally an ArrayList uses an Object[].
As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
Now, there is more room left, and the new element is added in the next empty space.
Since people really like the source code:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
Straight out of the JDK.
It uses an Object[], and makes a bigger array when the array gets full.
You can read the source code here.
ArrayList uses an Array of Object to store the data internally.
When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
When adding a new element, if the array is full, then a new array of 50% more the initial size is created and the last array is copied to this new array so that now there are empty spaces for the new element to be added.
Since the underlying data-structure used is an array, it is fairly easy to add a new element to the ArrayList as it is added to the end of the list. When an element is to be added anywhere else, say the beginning, then all the elements shall have to move one position to the right to create an empty space at the beginning for the new element to be added. This process is time-consuming (linear-time). But the Advantage of ArrayList is that retrieving an element at any position is very fast (constant-time), as underlying it is simply using an array of objects.
ArrayList has the basic data structure:
private transient Object[] elementData;
When we actually create an ArrayList the following piece of code is executed:
this.elementData = new Object[initial capacity];
ArrayList can be created in the two ways mentioned below:
List list = new ArrayList();
The default constructor is invoked and will internally create an array of Object with default size 10.
List list = new ArrayList(5);
When we create an ArrayList in this way, constructor with an integer argument is invoked and
create an array of Object with default size 5.
Inside the add method there is check whether the current size of filled elements is greater/equal to the maximum size of the
ArrayList then it will create new ArrayList with the size new arraylist = (current arraylist*3/2)+1 and copy the data from old to
new array list.
It uses an array, and a couple of integers to indicate the first value - last value index
private transient int firstIndex;
private transient int lastIndex;
private transient E[] array;
Here's an example implementation.
Typically, structures like ArrayLists are implemented by a good old fashioned array defined within the class and not directly accessible outside the class.
A certain amount of space is initially allocated for the list, and when you add an element that exceeds the size of the array, the array will be reinitialized with a new capacity (which is typically some multiple of the current size, so the framework isn't constantly re-allocating arrays with each new entry added).
The Java platform source code is freely available. Here's an extract:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient E[] elementData;
.
.
.
}
ArrayLists use arrays to hold the data. Once the number of elements exceeds the allocated array it copies the data to another array, probably double the size.
A (minor) performance hit is taken when copying the array, it's therefore possible to set the size of the internal array in the constructor of the array list.
Furthermore it implements java.util.Collection and and java.util.list, and it's is therefore possible to get the element at a specified index, and iterable (just like an array).
It uses an Object[]. When the array is full it creates a new array which is 50% bigger in size and copies current elements to new array. It happens automatically.
as i understand is that
ArrayList class implements List interface and
(as interface only extends other interface)
List interface extends Collection interface.
while talking about arraylist when we initialize in memory it reserve by default space 10 > and create array of Integer which you normally use. when this this array is full then the another array of interger is created which is greater then default size.
List<Integer> list = new ArrayList<>();
now in memory as => Integer[] list = new Integer[10];
now suppose that you enter 1,2,3,4,5,6,7,8,9,10 array is full now and what happen when you enter 11 in the memory another array of Integer is created which is greater then by default and all element in old array is copied in new array. Internally arraylist user Object[] array.
thats how arrayList work
Basic Data Structure which is used in an ArrayList is –
private transient Object[] elementData;
So, going by declaration it’s an array of Object.
When we actually create an arrayList following piece of code is executed –
this.elementData=new Object[initial capacity];
When we create an ArrayList, default constructor is invoked and will internally create an array of Object with default size, which is 10. Now, As we all know that unlike normal arrays, the size of the ArrayList grows dynamically. But how its size grows internally?
So what happens internally is a new Array is created with size 1.5 x currentSize and the data from old Array is copied into this new Array. Every time when it reaches ArrayList at maximum capacity then copy and destroy previous array make new array with new capacity (1.5 x old capacity).
For more details your can read my blog here.

what is the time complexity for copying list back to arrays and vice-versa in Java?

I am wondering what is the time complexity [in big O(n) notations] of ArrayList to Array conversion:
ArrayList assetTradingList = new ArrayList();
assetTradingList.add("Stocks trading");
assetTradingList.add("futures and option trading");
assetTradingList.add("electronic trading");
assetTradingList.add("forex trading");
assetTradingList.add("gold trading");
assetTradingList.add("fixed income bond trading");
String [] assetTradingArray = new String[assetTradingList.size()];
assetTradingArray.toArray(assetTradingArray);
similarly, what is the time complexity for arrays to list in the following ways:
method 1 using Arrays.asList:
String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed
income", "futures", "options"};
List assetList = Arrays.asList(asset);
method 2 using collections.addAll:
List assetList = new ArrayList();
String[] asset = {"equity", "stocks", "gold", "foreign exchange", "fixed
income", "futures", "options"};
Collections.addAll(assetList, asset);
method 3 addAll:
ArrayList newAssetList = new ArrayList();
newAssetList.addAll(Arrays.asList(asset));
The reason I am interested in the overhead of copying back and forth is because in typical interviews, questions come such as given an array of pre-order traversal elements, convert to binary search tree and so on, involving arrays. With List offering a whole bunch of operations such as remove etc, it would make it simple to code using List than Array.
In which case, I would like to defend me for using list instead of arrays saying "I would first convert the Array to List because the overhead of this operation is not much (hopefully)".
Any better methods recommended for copying the elements back and forth from array to list that would be faster would be good know too.
Thanks
It would seem that Arrays.asList(T[]); is the fastest withO(1)
Because the method returns an unmodifiable List, there is no reason to copy the references over to a new data structure. The method simply uses the given array as a backing array for the unmodifiable List implementation that it returns.
The other methods seem like they copy each element, one by one to an underlying data structure. ArrayList#toArray(..) uses System.arraycopy(..) deep down (O(n) but faster because it's done natively). Collections.addAll(..) loops through the array elements (O(n)).
Careful when using ArrayList. The backing array doubles in size when its capacity is reached, ie. when it's full. This takes O(n) time. Adding to an ArrayList might not be the best idea unless you know how many elements you are adding from the beginning and create it with that size.
Since the backing data structure of ArrayList is an array, and copying of an array elements is a O(n), it is O(n).
The only overhead I see is pollution of heap with those intermediate objects. Most of the time developers (especially, beginners) don't care about that and treat Java GC as a magic wand that cleans everything after them. My personal opinion is, if you can avoid unwanted transformation of array to list and vice versa, do that.
If you know beforehand the foreseeable (e.g. defined) size of a list, preallocate its size with ArrayList(int size) constructor to avoid internal array copying that takes place inside ArrayList when capacity is exhausted. Depending on a use case, consider other implementations, e.g. LinkedList, if you're only interested in consequent addition to the list, and iterative reading.
An ArrayList is fundamentally just a wrapper around an Object[] array. It has a lot of helpful methods for doing things like finding items, adding and removing items, and so on, but from a time complexity perspective these are no better than doing the operations yourself on a plain array.
If your hope is that an ArrayList is fundamentally more efficient than a manually managed array, it's not. Sorry!
Converting an array to an ArrayList takes O(n) time. Every element must be copied.
Inserting or removing an element takes O(m) amortized time, where m is the number of elements following the insertion/removal index. These elements have to be moved to new indices whether you use an array or ArrayList.
"Amortized" means average -- sometimes the backing array will need to be grown or shrunk, which takes additional time on the order of O(n). This doesn't happen every time, so on the whole the additional time averages out to an O(1) additional cost.
Accessing an element at an arbitrary index takes O(1) time. Both provide constant time random access.

How does ArrayList work?

What data structure does an ArrayList use internally?
Internally an ArrayList uses an Object[].
As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
Now, there is more room left, and the new element is added in the next empty space.
Since people really like the source code:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
Straight out of the JDK.
It uses an Object[], and makes a bigger array when the array gets full.
You can read the source code here.
ArrayList uses an Array of Object to store the data internally.
When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
When adding a new element, if the array is full, then a new array of 50% more the initial size is created and the last array is copied to this new array so that now there are empty spaces for the new element to be added.
Since the underlying data-structure used is an array, it is fairly easy to add a new element to the ArrayList as it is added to the end of the list. When an element is to be added anywhere else, say the beginning, then all the elements shall have to move one position to the right to create an empty space at the beginning for the new element to be added. This process is time-consuming (linear-time). But the Advantage of ArrayList is that retrieving an element at any position is very fast (constant-time), as underlying it is simply using an array of objects.
ArrayList has the basic data structure:
private transient Object[] elementData;
When we actually create an ArrayList the following piece of code is executed:
this.elementData = new Object[initial capacity];
ArrayList can be created in the two ways mentioned below:
List list = new ArrayList();
The default constructor is invoked and will internally create an array of Object with default size 10.
List list = new ArrayList(5);
When we create an ArrayList in this way, constructor with an integer argument is invoked and
create an array of Object with default size 5.
Inside the add method there is check whether the current size of filled elements is greater/equal to the maximum size of the
ArrayList then it will create new ArrayList with the size new arraylist = (current arraylist*3/2)+1 and copy the data from old to
new array list.
It uses an array, and a couple of integers to indicate the first value - last value index
private transient int firstIndex;
private transient int lastIndex;
private transient E[] array;
Here's an example implementation.
Typically, structures like ArrayLists are implemented by a good old fashioned array defined within the class and not directly accessible outside the class.
A certain amount of space is initially allocated for the list, and when you add an element that exceeds the size of the array, the array will be reinitialized with a new capacity (which is typically some multiple of the current size, so the framework isn't constantly re-allocating arrays with each new entry added).
The Java platform source code is freely available. Here's an extract:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient E[] elementData;
.
.
.
}
ArrayLists use arrays to hold the data. Once the number of elements exceeds the allocated array it copies the data to another array, probably double the size.
A (minor) performance hit is taken when copying the array, it's therefore possible to set the size of the internal array in the constructor of the array list.
Furthermore it implements java.util.Collection and and java.util.list, and it's is therefore possible to get the element at a specified index, and iterable (just like an array).
It uses an Object[]. When the array is full it creates a new array which is 50% bigger in size and copies current elements to new array. It happens automatically.
as i understand is that
ArrayList class implements List interface and
(as interface only extends other interface)
List interface extends Collection interface.
while talking about arraylist when we initialize in memory it reserve by default space 10 > and create array of Integer which you normally use. when this this array is full then the another array of interger is created which is greater then default size.
List<Integer> list = new ArrayList<>();
now in memory as => Integer[] list = new Integer[10];
now suppose that you enter 1,2,3,4,5,6,7,8,9,10 array is full now and what happen when you enter 11 in the memory another array of Integer is created which is greater then by default and all element in old array is copied in new array. Internally arraylist user Object[] array.
thats how arrayList work
Basic Data Structure which is used in an ArrayList is –
private transient Object[] elementData;
So, going by declaration it’s an array of Object.
When we actually create an arrayList following piece of code is executed –
this.elementData=new Object[initial capacity];
When we create an ArrayList, default constructor is invoked and will internally create an array of Object with default size, which is 10. Now, As we all know that unlike normal arrays, the size of the ArrayList grows dynamically. But how its size grows internally?
So what happens internally is a new Array is created with size 1.5 x currentSize and the data from old Array is copied into this new Array. Every time when it reaches ArrayList at maximum capacity then copy and destroy previous array make new array with new capacity (1.5 x old capacity).
For more details your can read my blog here.

Categories

Resources