Adding int to an array - java

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.

Related

What is the time complexity of the add and element in a Java Array?

Hello I am research about that, but I cannot found anything in the oracle website.
The question is the next.
If you are using an static Array like this
int[] foo = new int[10];
And you want add some value to the 4 position of this ways
foor[4] = 4;
That don't shift the elements of the array so the time complexity will be O(1) because if you array start at 0x000001, and have 10 spaces, and you want put some in the x position you can access by (x*sizeOf(int))+initialMemoryPosition (this is a pseudocode)
Is this right, is this the way of that this type of array works in java, and if its time complexity O(1)
Thanks
The question is based on a misconception: in Java, you can't add elements to an array.
An array gets allocated once, initially, with a predefined number of entries. It is not possible to change that number later on.
In other words:
int a[] = new int[5];
a[4] = 5;
doesn't add anything. It just sets a value in memory.
So, if at all, we could say that we have somehow "O(1)" for accessing an address in memory, as nothing related to arrays depends on the number of entries.
Note: if you ask about ArrayList, things are different, as here adding to the end of the array can cause the creation of a new, larger (underlying) array, and moving of data.
An array is somewhere in memory. You don’t have control where, and you should not care where it is. The array is initialized when using the new type[size] syntax is used.
Accessing the array is done using the [] index operator. It will never modify size or order. Just the indexed location if you assign to it.
See also https://www.w3schools.com/java/java_arrays.asp
The time complexity is already correctly commented on. But that is the concern after getting the syntax right.
An old post regarding time complexity of collections can be found here.
Yes, it takes O(1) time. When you initialize an array, lets say, int[] foo = new int[10],
then it will create a new array with 0s. Since int has 4 bytes, which is 32 bits, every time assign a value to one element, i.e., foo[4] = 5, it will do foo[32 x input(which is 4)] = value(5); That's why array is 0-indexed, and how they assign values in O(1) time.

User defined Array dimensional and size

I have unsolvable task, I have task, where i have insert random number to array. The user can choose if array is 1D, 2D, 3D,size of array is optional . I tried everything but withot success. I can not use ArrayList.
Thank you for help.
double[] array= new double[size];
for ( int i;i<dimensional;i++)
{
double[] array= new double[size];
}
Edit:
I mind if is effective way to create array with 1D and then add to this array one or more dimension.
Multi-dimensional arrays in java are essentially just arrays of arrays. The user provides the number of dimensions and sizes at runtime so you need to dynamically build this array at this point. It's a strange problem, and not one that you would try to solve with arrays in production code, but nevertheless it should be possible. Try the accepted answer for this question, it seems like a pretty good attempt.
So, an "unsolvable" task ... well, as long as you work with primitive types and the dimension can be theoretically any number (only limited by memory available), you may be right.
You can however use some kind of object (Java is an object-oriented language) and solve the task rather easily. Basically, you might want a tree structure with nodes. You can even write a constructor that sets fixed sizes for every level and give no direct accessors to the array as a whole. Start with:
class Node {
double payload;
Node[] children;
}
I don't really understand what do you want to do with that, but it pretty much fits the idea of N-dimensional array.
Another solution: Make the array one-dimensional, but using the sizes of the individual dimensions, you can calculate the correct index. Of course, it will require you to handle the logic.
E.g. in a 2D array of 3x3 size, you can use a 1D array of 9 size and use first three indexes for first row, next three for second row, last three for third row. You can then use a cycle like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//arr[i * 3 + j] = ...
}
}

Techniques to redimension an array in Java : is "nullifying" the array bad?

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 .

Arraylist vs Array with custom objects in java

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).

Add a value to an array?

I've just created a new array that is one larger than my previous array and I want to copy the values in my first array into my new one. How do I add a new value to the last index of the new array?
This is what I've tried:
public void addTime(double newTime) {
if (numOfTimes == times.length)
increaseSize();
times[numOfTimes] = newTime;
}
I would recommend trying to use an object such as java.util.List rather than raw arrays. Then you can just do:
times.add(newTime) and it handles the sizing for you.
Why not you use System.arraycopy function.
increaseSIze()
{
double [] temp = new double[times.lebgth+1];
System.arrayCopy(times,0,temp,0,times.length);
times=temp;
}
after that you have times array with 1 increased size.
To set a new value to the last index you can do
times[times.length - 1] = newTime;
Array indices go from 0..n-1.
array[array.length - 1] will address the value at the end of the array.
The last item of an array is always at myArray.length - 1. In your case the last element from the times array is times[times.length - 1]. Have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for more information about arrays.
But more importantly: If you're trying to change the capacity of your array, you are most likely using the wrong data structure for the job. Have a look at Oracle's Introduction to Collections (and especially the ArrayList class if you need an array-like index to access elements).
why wouldn't you want a java.util.ArrayList for this requirement? Practically, there won't be a need managing its size. You just simply do this:
List<Double> list = new ArrayList<Double>();
list.add(newTime);
Consider Arrays.copyOf if working with arrays is a constraint:
import java.util.Arrays;
...
private void increaseSize() {
// Allocate new array with an extra trailing element with value 0.0d
this.times = Arrays.copyOf( times, times.length + 1 );
}
...
Note that if you are doing this type array management often and in unpredictable ways, you may want to consider one of the Java Collection Framework classes such as ArrayList. One of the design goals of ArrayList is to administer size management, much like the JVM itself administers memory management.
I've developed an online executable example here.

Categories

Resources