add elements from one array to "empty array" - java

I'm new to arrays in java, so my question might seem simple to all of u
I have two arrays:
int[] newarray = new int[] {1,2,3,4}
int[] result = new int[4] // array with space for 4 elements
i=0
My question is: How do I add elements from newarray to result? For example, how do i add newarray[i]? There seems to be no add function like in python unless you use ArrayLists. Also is it possible to add elements from an array to an arraylist, or doesn't they work together? Hope to get some clarification :)

To set the ith element in result to the ith element in newarray, do the following:
result[i] = newarray[i];
In addition, you can copy over the entirety of the array using arraycopy:
System.arraycopy(newarray, 0, result, 0, newarray.length);
See also:
Arrays - The Java™ Tutorials
arraycopy() in Java

Use System.arrayCopy to copy arrays. Example:
System.arraycopy(newarray, 0, result, 0, newarray.length)
The first argument is the source array, then the source position, then the destination array and destination position, and the length.

int[] newarray = new int[] {1,2,3,4}
int[] result = new int[newarray.length];
for(int i=0;i<newarray.length;i++)
result[i]=newarray[i];

Lets say you want to assign the third value in newarray to the third index in result.
That would be like:
result[2] = newarray[2]

System.arraycopy(newarray, 0, result, 0, newarray.length);
or you can do it manually
for(int i = 0; i < newarray.length; i++) {
result[i] = newarray[i];
}
to work with Arrays, you can use
Arrays.asList(Object[] a);

Either copy elements one at a time in a loop or use System.arraycopy.
Understand that an array in Java is like an array in C in that it's fixed length (there are other classes like ArrayList for variable-length use). So you don't "add" a new element, you simply assign a value (x[i] = something;) to an existing element (which was initialized to zero when the array was created).
To my knowledge there's no "add all elements of this array" method on ArrayList, so to do that you'd have to loop through the array and add the elements one at a time. There are methods to go the other direction.

This should also work:
Arrays.asList(result).addAll(Arrays.asList(newarray));
Returns a fixed-size list backed by the specified array. (Changes to
the returned list "write through" to the array.)
Using static imports:
asList(result).addAll(asList(newarray));

Related

Get size of second dimension while first dimension is empty [duplicate]

Well, that might be a strange question, and maybe just because I'm not familiar enough with Java.
So, I declared a 2D int array:
int[][] arr = new int[0][10]
Now, as you can see, the second dimension's length is 10, while the first dimension's length is 0. I'm not sure how Java treats these kind of arrays, but the compiler doesn't produce any errors, which means it's a legit declaration.
Well, I passed the array to some function, and I want to retrieve from within the function, the length of the second dimension.
Of course something like:
arr[0].length
won't work. is there another way to do this?
The objects created by new int[0][10] and new int[0][20] are equivalent. There is no logical "second dimension" here. Effectively you're running something like this:
int[][] createArray(int d1, int d2) {
int[][] ret = new int[d1][];
for (int i = 0; i < d1; i++) {
ret[i] = new int[d2];
}
return ret;
}
Now if you translate that into your scenario, you'll end up with code which never reads d2.
If you want to represent a general-purpose rectangular array (instead of an array of arrays) you might want to consider creating your own type for it.
Arrays in Java, and most every other programming language, are zero-based. Consider this 2D array:
int[][] arr = new int[1][10];
This means that there is one row and ten columns in it.
Now, consider this array:
int[][] arr = new int[0][10];
This means that there are zero rows and (an irrelevant amount of columns) in it.
If you try to index into the second array, you'll find that you can't - an array of length zero has no starting point.
The compiler sees it as valid because you declared dimensions with it, but you won't be able to actually use it in any meaningful way in Java.
There is no such thing as the length of the second dimension. Consider:
int[][] arr = new int[10][10];
arr[5] = new int[42];
What is the length of the second dimension? 10 or 42?
No. It doesnt work this way. arr is an array with ten elements, each of which must be a reference of an int array (or null). That's all there is to say.

How can I make an array of my arrays in Java? (WITHOUT ArrayLists)

I have a few multidimensional arrays of type char[][].
Eg..
char[][] ARRAY_1 = {
{'.','#'},
{'$','#'}
}
char[][] ARRAY_2 = {
{'.','#'},
{'$','#'}
}
And I want to make an array or list of some sort such as
ARRAY = {ARRAY_1,ARRAY_2,...}
so I'll be able to put in ARRAY[1] (or something similar) and have it return the entire char[][] ARRAY_1
I am very new to programming with Java so I'm not sure what the best way to do this is.
Edit: I've just found out I'm not allowed to use ArrayLists.
Direct answer: use ArrayList<char[][]> or char[][][].
Basically, you create an ArrayList that holds your 2 dimensional arrays or a 3 dimensional array of chars.
List<char[][]> array = new ArrayList<>();
or
char[][][] array = char[length][][];
To add the arrays, you just use the following:
array.add(arrayOne); //for an ArrayList
array.add(arrayTwo);
or
array[0] = arrayOne; //for an array
array[1] = arrayTwo;
To get the arrays, you just use the following (where the number is the index):
array.get(0); //for an ArrayList
array.get(1);
or
array[0]; //for an array
array[1];
Check out the ArrayList javadoc for more information.
(edit: variable changed to match naming conventions)
So ... if you are not allowed to use lists ... this is one way to make an array of existing arrays.
char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};
Insight #1: an N-dimension array in Java is an array of N-1 dimension arrays (assuming N > 1).
Insight #2: arrays are indexed from zero.
How would I call the arrays individually again later on?
You still have the names of the original arrays ... in your example.
Base on insight #1":
char[][] ARRAY_1_AGAIN = ARRAYS[0];
System.out.println(ARRAY_1 == ARRAY_1_AGAIN); // prints true
Since ARRAY_1 is the first subarray of ARRAY (as per the previous example), we need to use ARRAYS[0] (not ARRAYS[0]) to access it.
Try this:
List<char[][]> list = new ArrayList<>();
list.add(ARRAY_1);
list.add(ARRAY_2);
Or
char[][][] ARRAY = new char[length][][];
ARRAY[0] = ARRAY_1;
ARRAY[1] = ARRAY_2;
Or
char[][][] ARRAY = new char[][][]{ARRAY_1, ARRAY_2};
Further reading:
ArrayLists in Java
You are using a Jagged Array...
Also try this
char[][] array = new char[5][];
array[0] = array1;
array[1] = array2;
Regards

Can we add elements in an array dynamically and also print it when the size is unknown, in java

Adding elements to an array in java ,given the size, is easy to code but doing it dynamically poses a problem .
Ex:
Int a[]= new Int[5];
a[0]=0;
a[1]=2;
a[2]=2;
a[3]=3;
a[4]=4;
Here(in the above example) we know the size, so I can assign the values. What If don't know how many values I have to add, in some cases it could be 5 and some other it might be 100.
So for such a situation I would need an array which will take input dynamically(as many as I input) or on spot.
My question is how to make an array dynamic in Java?
It could be done using List, but is there a way using array?
Please help me out
You can't allocate dynamically an array, but you can always create a new one when this one is full. This is a method to call when the array is full. it will return a new array with more elements and will get the elements from the old array:
public int[] createNewArray(int[] oldArray){
int[] newArray = new int[oldArray.length * 2];
for(int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}
return newArray;
}

Remove "hole" in array after remove item

I need to delete some objects from an array if they meet a condition.
After removing the object from the array I need the array to have no "holes", meaning I need to shrink the array: not the array size, but reducing the number of objects it contains.
It's okay if there are null values at the end of the array after removing objects.
Which would be more efficient?
Copying the array into new array
Iterating over the array and shift the elements over the "hole" created by removing an object
I must use an array, I cannot use a List implementation.
Use an ArrayList, this will allow you to dynamically change the size of your structure.
If you don't want to use ArrayList yuor solution is fine. But instead of copying your array, create a new empty one with the size of your array and then populate it in a for loop.
1) You can swap deleted element with the last element and make something like size--
2) If you can't swap you have to use System.arraycopy(...) method multiple times to copy parts of array to new array.
public static Object[] deleteElement(Object[] oldArray, int position) {
Object[] newArray = new Object[oldArray.length - 1];
System.arraycopy(oldArray, 0, newArray, 0, position);
System.arraycopy(oldArray, position + 1, newArray, position, newArray.length - position);
return newArray;
}
Based on your requirements,
i need that my array will be without any "holes" so i need to "shrink" that Array,
you must create a new array and move the remaining objects to it. Arrays are a fixed-size construct. You cannot "shrink" an array. You can only allocate new memory and move the elements to the new array.
EDIT: You should alter your question to include the information about allowing null at the end of the array. In that case, moving the elements back 1 index would be better since it eliminates memory allocation (which is expensive) and will have on average n/2 operations (assuming random removal) as opposed to n.
Both of your solutions are O(N) complexity, except the first one require another O(N) memory space. So the second one is slightly better if you really required to work on Array.
If you're working on an array of element that require frequent add and remove in the middle, I would suggest you use Linked-List implementation, so that it can give you constant time of adding and removing any element in your array.
Here's a simple example using System.arraycopy:
Integer[] i1 = new Integer[] {1, 2, 3, 4, 5};
Integer[] i2 = new Integer[4];
// Copy everything, except the third value of i1:
System.arraycopy(i1, 0, i2, 0, 2);
System.arraycopy(i1, 3, i2, 2, 2);
for (int j : i2)
{
System.out.println(j);
}
Some pseudocode
Step 1: Find all the objects from the array that match whatever you want it to match and overwrite them with a unique value (for example: if your array only contains integers 0 or higher, overwrite the ones you want to remove with -1)
Step 1.5: keep a counter of the AMOUNT of removes you did
Step 2: Create a new array with the size of (oldarray.size - counterFromStep1.5)
Step 3: for each non-empty element in oldarray THAT IS NOT (the remove integer), add it to new array

How does this Java code work?

public static void main(String[] args)
{
int [][]shatner = new int[1][1];
int []rat = new int[4];
shatner[0] = rat;
System.out.println(shatner[0][3]);
}
surprised, The output is 0, why Java doesn't check this kind of indexOutOfBound error?
Don't be surprised. shatner[0] is an array (rat) and happens to be of length 4. So shartner[0][3] is rat[3] which happens to be 0..
Where do you see an "indexOutOfBound error"? The code does the following:
Initalize an array (size 1) of int arrays (size 1), i.e. a 2D array, contents are intialized with 0
Initalize a array of int, size 4, content is intialized with 0
set the single element of the 2D array to the size 4 1D array
access the last element of the first array in the 2D array, which is 0
There is nothing going out of bounds.
The 0th row in the shatner array gets reinitialized to int[4].
There is no index out of bounds error. shatner is an array of arrays. You replaced the first array of length one with a new one of length four. So now shatner[0][3] is a perfectly legit place in memory.
It's not that Java doesn't check the IndexOutOfBoundsException. It's that the answer SHOULD be zero. The key line is
shatner[0] = rat;
Since that means that the 0th index of shatner is pointing to an array of length 4, shatner[0][4] is totally valid.
I'm thinking it's because java's arrays are working a bit differently than expected. You initialize shatner to [1][1], meaning something like, {{0},{0}} in memory.
However, you then assign an integer to the first element, turning it into {{0,0,0,0},{0}} in memory, so Java is addressing the newly assigned index.
Arrays need not be rectangular in Java. This is a jagged array and is perfectly fine.

Categories