How to create an array that extends itself dynamically? - java

How to create an array that extends itself. I don't want to use the classes like ArrayList and Vector etc to do this. Instead i need to generate an array that extends it's size upon adding elements to it. This is question by my teacher.
Say for example, i want an int[] which extends it's size.
For instance, the user want to enter the student IDs into an array. The array has no fixed size since there are no fixed no. of students in this case. When the user says he wants one more, the array's size should be incremented by one.
Any answer is appreciated.

Arrays are fixed in length, you can not increase or decrease the size of array.
What you can do create new array with larger size and copy the values using Arrays#copyOf source array to new destination array.
Note: Arrays#copyOf internally call System.copy which does shallow copy.

Here is a useful link for your teacher, from the docs:
An array is a container object that holds a fixed number of values
of a single type. The length of an array is established when the array
is created. After creation, its length is fixed.
The only option to do that without ArrayList/Vector.. is creating a new array and copying the values to it.

Your description, 'When the user says he wants one more, the array's size should be incremented by one.' is just a pointer array, which is LinkedList in java.

Whatever your teacher says there is no way to resize a array dynamically without creating a new array with edited size. I don't think any language supports this requirement. Just create a new array and copy the existing one.

I think i'll have to re-initialize the array with an incremented size but before that, i think i'll have to copy all those elements into a temporary array and then again copy them into the original array whose size is changed.
If this is correct, my teacher might be looking for this. But that degrades the performance though.

Related

Java array of size 0

So I just discovered that Java allows us to create arrays of size 0. Does that mean that the array is both empty and full at the same time? I figured this out while working on an array based implementation of a priority queue. Would it be right to say that it is empty and full at the same time when calling methods checking for this? Or should I not allow the creation of an array of size 0? Thanks.
Java arrays have no definition of full or of empty. Consider
int[] foo = {0};
int[] bar = new int[1];
Is foo full because it has a value assigned to its only position?
Is bar empty because it has no values assigned?
Both arrays are the same, they both have one value stored and in both cases the contain the value 0.
Full implies you can't add any more items, you can never add new items to java arrays, just replace existing items, so either all arrays are full or full does not make sense for a java array. I say it is the second.

Instantiating an ArrayList of ArrayLists

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.

ArrayList in Java when storing large objects

I came across this interview question about arraylist in Java, and I feel it is quite interesting but no clue how to answer it:
What attention should be paid when using arrayList to store large object?
I wonder if we should answer this question in the regard of time/space coplexity?
Thanks
All objects in Java are stored as references, in containers and variables, etc, so in C++ terms, all containers only store pointers to the objects. In such a situation, the size of the object should be irrelevant for most if not all use cases.
Internally ArrayList uses Object[]. Once it reaches max capacity, it creates a new array of size 1.5 times the original and will copy from old array to new array. May be interviewer wanted to check about the cost of this copy with large objects
ArrayList: how does the size increase?
check ensureCapacity() - http://www.docjar.com/html/api/java/util/ArrayList.java.html
ArrayList supports dynamic arrays that can grow as needed.
In Java, arrays has a fixed length this means after the arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may dont know the size until the runtimeso that in this situation we used ArrayList.
ArrayList can dynamically increase or decrease in size. 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.
also, be aware that Arraylist store only objects.

The array size in Java is fixed after declaration?

I wanted to know if the Java arrays are fixed after declaration. When we do:
int a[10];
and then can we do:
a = new int [100];
I am unsure if the first statement already allocates some memory and the second statement allocates a new chunk of memory and reassigns and overwrites the previous reference.
Yes it is:
The length of an array is established when the array is created. After
creation, its length is fixed.
Taken from here.
Also, in your question the first scenario: int a[10] is syntactically incorrect.
The second statement allocates a new chunk of memory, and the previous reference will eventually be garbage collected.
You can see it by yourself using a java debugger. You will notice that a will point to a different location after the second statement executes.
Good luck with your H.W.
Array have fixed length that is determined when you create it. If you want a data structure with variable length take a look at ArrayList or at LinkedList classes.
Array has fixed length but if you want the array size to be increased after this:
private Object[] myStore=new Object[10];
In normal way you have to create another array with other size and insert again all element by looping through the first array,but arrays class provide inbuild method which might be useful
myStore = Arrays.copyOf(myStore, myStore.length*2);

Is it possible to create an open-ended array?

I was wondering if I could create an array without having to enter a value. I don't fully understand how they work, but I'm doing an inventory program and want my array to be set up in a way that the user can enter products and their related variables until they are done, then it needs to use a method to calculate the total cost for all the products. What would be the best way to do that?
Use an ArrayList.
This will allow you to create a dynamic array.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
Here is an example/overview:
http://www.anyexample.com/programming/java/java_arraylist_example.xml
Yes, you can do this. Instead of using a primitive type array, for example new int[10], use something like the Vector class, or perhaps ArrayList (checkout API docs for the differences). Using an ArrayList looks like this:
ArrayList myList = new ArrayList();
myList.add("Item 1");
myList.add("Item 2");
myList.add("Item 3");
// ... etc
In other words, it grows dynamically as you add things to it.
As Orbit pointed out, use ArrayList or Vector for your data storage requirements, they don't need specific size to be assigned while declaration.
You should get familiar with the Java Collections Framework, which includes ArrayList as others have pointed out. It's good to know what other collection objects are available as one might better fit your needs than another for certain requirements. For instance, if you want to make sure your "list" contains no duplicate elements a HashSet might be the answer.
http://download.oracle.com/javase/tutorial/collections/index.html
The other answers already told how to do it right. For completeness, in Java every array has a fixed size (length) which is determined at creation and never changes. (An array also has a component type, which never changes.)
So, you'll have to create a new (bigger) array when your old array is full, and copy the old content over. Luckily, the ArrayList class does that for you when its internal backing array is full, so you can concentrate on the actual business task at hand.

Categories

Resources