I am trying to convert a section of code from using an ArrayList of custom objects to a regular array.
Previous my definition was
ArrayList<Room> rooms = new ArrayList<Room>();
Which I have now changed to
Room[] rooms;
Previously I used the below line to add items to the array list
rooms.add(new Room(1,1,30,false,true,true,false));
But I am now struggling to find the way I should simply add individual items to the array throughout code.
I think you are best sticking with an arrayList here, but just to give you a bit more light on it.
To do what you are trying to do, you will have to keep a index integer which will just point to the current position in the array, then when you add you can increment this and add the new object into the next poisition.
When you get to the maximum size of your array, you will need to expand it.
You will find that there has been questions on expanding an array which have been asked already and you can find the answers here:
Expanding an Array?
If you can live with a fixed-size array, that gives you at least a slight chance of success. If not, you can't beat ArrayList and if your mission is to succeed without reimplementing it, then it is an impossible mission.
You should really give more insight into the exact rationale for rewriting your code like that, it would give us some chance to properly help you.
I can recommend:
Use Arraylist as Long you Need to insert Elements. Once th Array is final Convert to Array.
If you need to increase the size of the array when adding another element, you have to construct another array with the size of the old array +1.
Afterwards, you would copy the contents of the old array over to the new array (the bigger array).
Related
This question already has answers here:
Resize an Array while keeping current elements in Java?
(12 answers)
Closed 3 months ago.
As the title, how can I resize array in java, without importing any library, including ArrayList, Arrays.copyOf ...etc.
Also, I have to resize again and again in my program, with the unknown input data.( i.e. I have a small array, but when the data increasing, how can I resize it?)
Unfortunately, you cant resize an array in java.
Some things you could do are:
When new data is taken in, make a new array and copy the old array + the new data.
Use an ArrayList which makes the array bigger as you add data to it.
Use java.util.Arrays.copyOf(...). This returns a bigger array with the contents of the previous array.
Java does not have a "resize" option for allocated storage. You must allocate new storage of the required size and copy the data from the old storage to the new.
You can use System.arraycopy() to copy the data. The ArrayList and Vector classes automatically perform these reallocate and copy operations, so if you don't use them, you are reinventing the wheel.
java.lang.System is, of course, automatically imported into every java program, so, as required, you don't need import java.lang.System; to implement this.
a array is by definition fixed in size, I know many modern languages let you assign the length and change the length dynamically
but I think what you are looking for is a Vector
https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
it allows O(1) access (like the array) while beeing dynamic in length
You can not increase the size of an array once it is declared. So you have to use Collection framework in java, may be ArrayList or LinkedList.
That is what is the difference between Array and ArrayList. In ArrayList you can add element dynamically,no need to increase it's size.
you could use forEach to copy the values to the enlarged new array
IntStream.range( 0, oldArray.length ).forEach( i -> newArray[i] = oldArray[i] );
I'm learning Java and surprisingly I found out that Java arrays are not dynamic - even though its cousing languages have dynamic arrays.
So I came out with ideas to kind of imitate a dynamic array in java on my own.
One thought I had was to copy the original array references to a temporary array, then turn the original array to null, re-set its index to a bigger value and then finally re-copy the values from the temporary array.
Example.:
if(numberOfEntries == array.length){
Type[] temp = new Type[numberOfEntries];
for(int x=0; x < numberOfEntries; x++){
temp[x] = array[x];
}
array = null;
array = new Type[numberOfEntries+1];
for(int x=0; x < numberOfEntries; x++){
array[x] = temp[x];
}
I know that this can result in data loss if the process is interrupted, but aside from that, is this a bad idea? What are my options?
Thanks!
Your idea is in the right ballpark. But for a task that you propose you should never implement your own version, unless it is for academic purposes and fun.
What you propose is roughly implemented by the ArrayList class.
This has an internal array and a size 'counter'. The internal array is filled when items are added. When the internal array is full all elements are copied to a bigger array. The internal array is never released to the user of the class (to make sure it's state is always valid).
In your example code, because an array is a pointer, you don't really need the temp array. Just create a new one, copy all elements and save the pointer to it as your array.
You might want to look into thrashing. Changing the size of the array by 1 is likely to be very inefficient. Depending on your use case, you might want to increase the array size by double, and similarly halve the array when it's only a quarter full.
ArrayList is convenient, but once it's full, it takes linear time to add an element. You can achieve something similar to resizing with the ensureCapacity() method. I'd recommend becoming more familiar with Java's Collections framework so you can make the best decisions in future by yourself.
Arrays are not dynamic their size can't change dynamically and right now you aren't changing the same object, you are replacing smaller size object with larger size object
int[5] Arr = new int[5] ; // Create an array of size 5
Arr = new int[10] ;// you assigned the different objects. It is not the same object.
So, we can't change the size of the array dynamically. You can use ArrayList for the same.
But keep try !!!
Please take a look at java.util.ArrayList which is dynamically, it is part of the Collections framework. Making the Array dynamically should be slower and error-prone.
Have you heard about time complexity , do you know how much time complexity you are increasing, Every time you are copying old array element to new array let you have 1 million element in array then think about copying time of element of one array to another array.
One more thing i want to tell you, ArrayList implementation used same logic except new length that you are using .
I am currently making a tiny little program that should be able to select a random element i put into the array using a Random of course (For practice purposes) and when a element in the array has been chosen at random. i want to remove this element in the array, so how do you remove a element in a array the easiest way?
Its the only thing i want to know. I got everything else sorted. It's just removing the element it has chosen (the random takes a random number between 0 and the amount of elements in the array, so if it chooses 0, it will take the first element in the array, and so on)
You can use ArrayList which support remove or add function, which actually is an resizable array.
You can't remove an element from an array. You can replace it with some other value that indicates "nothing", null for example.
An easy solution is to convert the array into a list.
list = Arrays.asList(array);
Remove any element from the list and then revert it back to an array using
array = list.toArray();
Hope it helps.
Use List instead of Array, and if you want to stay on Array than there is 2 solution,
Create another Array ignoring your element which you want to delete.
create a List using Array.asList(...) than remove element from list and convert back to Array.
but according to me its better for you as well as java to use List. because List provide a many build-in functions.
First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.
I'm currently in the process of creating an OBJ importer for an opengles android game. I'm relatively new to the language java, so I'm not exactly clear on a few things.
I have an array which will hold the number of vertices in the model(along with a few other arrays as well):
float vertices[];
The problem is that I don't know how many vertices there are in the model before I read the file using the inputstream given to me.
Would I be able to fill it in as I need to like this?:
vertices[95] = 5.004f; //vertices was defined like the example above
or do I have to initialize it beforehand?
if the latter is the case then what would be a good way to find out the number of vertices in the file? Once I read it using inputstreamreader.read() it goes to the next line until it reads the whole file. The only thing I can think of would be to read the whole file, count the number of vertices, then read it AGAIN the fill in the newly initialized array.
Is there a way to dynamically allocate the data as is needed?
You can use an ArrayList which will give you the dynamic size that you need.
List<Float> vertices = new ArrayList<Float>();
You can add a value like this:
vertices.add(5.0F);
and the list will grow to suit your needs.
Some things to note: The ArrayList will hold objects, not primitive types. So it stores the float values you provide as Float objects. However, it is easy to get the original float value from this.
If you absolutely need an array then after you read in the entire list of values you can easily get an array from the List.
You can start reading about Java Collections here.
In java arrays have to be initialised beforehand. In your case you have the following options:
1) Use an ArrayList (or some other implementation of List interface), as suggested by others. Such lists can grow dynamically so this will help.
2) If you have control over the file format, add information on the number of vertices to the beginning of the file, so you can pre-initialise your array with correct size.
3) If you don't have control over it, try guessing the number of vertices based on file size (float is 4 bytes, so maybe divide File.length() by 4, for example). If the guessed number is too small, you can dynamically create a bigger array (say, 120% of the previous array size), the copy all data from previous array into the new one and carry on. This may be costly but if your guessing of array size is precise it will not be a problem.
We might be able to give you more ideas if you give us more information on file format and/or how this array of vertices going to be used (like: stored for a long time, or thrown away quickly).
No, you can't fill in uninitialized array.
If you need a dynamic structure that allows storing data + indexes (which seem to be important in your case), I would go for Map (key of Map would be your index):
Map<Integer, Float> vertices = new HashMap<Integer, Float>();
vertices.put(95, 5.004f);