Pass array by reference from a certain index on - java

In c, you can pass an array by reference from a certain index (say i) on simply by passing the address of the i-th element.
Now I was wondering if & how I can create a similar structure to work in Java.
I'm currently implementing an inplace radix-4 fft in java for which I'm making a recursive call on only parts of the initial data array.
So say I have a data array a= [1,2,3,4,5,6,7,8], I want to make 4 calls, each receiving a 4th of a as a parameter such that I can perform in-place modifications to a.

It cannot be done in Java with a 1-dimensional array directly.
You can do it with a multi-dimensional array.
For example:
int[][] a = {{1,2},{3,4},{5,6},{7,8}};
Now you can pass a[i] to your method, which can modify its elements.
Or you can create a List view of the array using Arrays.asList(). Then you can use subList() to pass parts of that List to your method, and modify these parts. These modifications will be reflected in the original array.
For example:
public static void changeSubList(List<Integer> list) {
list.set (0, 150);
}
public static void main (java.lang.String[] args)
{
Integer[] array = {1,2,3,4,5,6,7,8};
List<Integer> list = Arrays.asList (array);
changeSubList(list.subList (0, 2));
changeSubList(list.subList (2, 4));
changeSubList(list.subList (4, 6));
changeSubList(list.subList (6, 8));
System.out.println (Arrays.toString (array));
}
Output:
[150, 2, 150, 4, 150, 6, 150, 8]
The only issue is that you can't use an array of primitives.

Have a method that takes an array and start and end index as parameters. This is a pretty common idiom, but of course it expects the method to behave nicely and not read outside of its allowed indices.
It's simple, performant and pretty much the only realistic way in Java. All you have to worry about is buggy methods corrupting the array, but that shouldn't happen right?

You can't really do that "out of the box.
You could create an" array view" class that only gives access to a specific range.
But you can't create sub arrays without allocating memory and copying entries.

Related

Java array vs Array

It's been a while since I took a proper course on Java and I'm hoping someone can confirm/correct my understanding.
Consider the variables int[] arr and ArrayList arrLi:
arr has pointers directly to each component. arr[3] goes directly to the fourth element whereas arrLi.get(3) would have to traverse through the first three elements to get to the fourth.
Reassigning a component, such as a[3] = 0, does not rewrite the entire array.
Each time you want to add an element to arr, you would need to rewrite the entire array. For example, if there are 100 elements in arr, you have to make a new array with size 101 and copy all the elements from arr then add the new one. If you later decide to add yet another element, you'd have to go through the whole process again to add the 102-nd element.
arrLi adds (to end, front, or middle) and removes elements very efficiently because all it does is add/remove nodes and adjust the links.
ArrayList is a resizable array implementation of the List interface. Therefore fetching an element does not require traversing the previous elements.
Rewriting a value does not require rewriting the entire array in either case.
Yes, an array does need to be recreated if you need more space.
While it is called a list, ArrayList internally behaves much more like an array. ArrayList sometimes needs to be resized, meaning the underlying array needs to be recreated. However, this happens infrequently enough to not affect the average performance of an ArrayList over an array by much.
Please refer to https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html for more information

How to add an element at the end of an array?

I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List.
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List<T> interface, which represents a list of instances of the class T. The easiest and most widely used implementation is the ArrayList. Here is an example:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size().
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer), then you can use one of the NIO Buffer classes like java.nio.IntBuffer. These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
one-liner with streams
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();

Adding to an already set/filled array

Is it possible to do this? I want to be able to give the user the option to add another element to the array which is set to the length 5 and has already been filled. I believe this will increase the array length by 1? Also, please know that I know how to do this in ArrayList. I want to be able to do this in a normal array.
I heard that Arrays.copyof() can help do this but I don't understand how?
You can't add one more element if your array is filled.
You need to build a bigger array and copy the values from the old array to the new one. That's where Arrays.copyOf comes in handy.
For performance reason, it would be better to add more than 1 empty cell each time you rebuild a new array. But basically, you will build your own implementation of ArrayList.
In an ArrayList you can just add another value without having to do anything. Internally, the ArrayList will create a new, larger array, copy the old one into it, and add the value to it.
If you want to do this with an array, you will need to do this work yourself. As you are thinking, Arrays.copyOf() is a simple way to do that. For instance:
int[] a = {1,2,3,4,5};
System.out.println(a.length); // this will be 5
System.out.println(Arrays.toString(a)); // this will be [1, 2, 3, 4, 5]
int[] b = Arrays.copyOf(a, 10);
System.out.println(b.length); // this will be 10, half empty
System.out.println(Arrays.toString(b)); // this will be [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
import java.util.Arrays;
int[] myArray = new int[]{1,2,3,4,5}; //The array of five
int[] myLongerArray = Arrays.copyOf(myArray, myArray.length + 1); //copy the original array into a larger one
myLongerArray[myLongerArray.length-1] = userInput; //Add the user input into the end of the new array
If you're going to be adding a lot of elements, instead of making the array one element larger each time, you should consider doubling the size of the array whenever it gets full. This will save you copying all of the values over each time.
Here is another example of using copyOf()
List<Object> name = ArrayList<Object>();
name.add(userInput);
It's much better, more efficient. Also has convenient methods for use (especially add(Object), indexOf(Object), get(Object), remove(Object)).

Is there a quick way to create an array of return codes from another array?

Suppose I have an array of objects from the MyClass class:
MyClass myClassArray[] = {
new MyClass(0, 1),
new MyClass(2, 3),
new MyClass(4, 5),
new MyClass(6, 7)
};
Here, the MyClass constructor fills in two fields, which we shall call field1 and field2. Suppose now that I want to fill in an array containing the value of field1 from each object in myClassArray (so the array will contain the values 0, 2, 4, 6). The following does not work:
field1Array = myClassArray.getField1();
Is there a quick 1-line way to fill in the new array using return codes from methods belonging to objects in the original array? Obviously, I can do this using a for loop, but I'd rather make use of the features of the language, if they exist.
You will need to loop unless you are using Java 8+ which adds lambda expressions to the language, in which case you can map your array to a new array:
int[] field1Array = Arrays
.stream(myClassArray)
.mapToInt(MyClass::getField1)
.toArray();
This is admittedly a theoretical answer since Java 8 will not be officially released until Q1 next year.
Currently there are no other language features than a plain old and simple for loop.
With Java 8 there may be lambda expressions and perhaps some helper method for Collection which will do what you want. But Java 8 is not yet released.
No, as far as I know, in Java, there is no way to call a method on every element of the array, apart from using a loop.
int[] field1 = new int[myClassArray.size()];
for(int i = 0; i < myClassArray.size(); i++){
field1[i] = myClassArray[i].getField1();
}
Your approach has to use a loop (while, here for), because you can't run through an array without one. Sure you can handle each element of the array one by one. But this would be a nightmare for a fair size of elements in the array.

Reference (not copy) a subrange of a one-dimensional array?

Suppose I have the following method signature
int f (int[] values)
and I call it like this:
int[] myValues = {1,2,3,4,5}
f (myvalues)
then, since arrays are objects, and objects are reference types, f receives a reference to the ints, and can change their value so the caller can see the changes.
Now how can I then call f in a way that it receives a reference to the array elements 2,3,4 (i.e. subrange from index 1 to 3 inclusive) without copying myValues?
Something like
f ((int[]) myvalues[1])
which of course does not compile (and would leave open which size the array would have) but might transport the idea I am looking for?
In other languages, I could use pointer arithmetics to calculate the address of myValues[2], and treat it a the beginning of an array of integer, and pass an explicit count parameter. (Quite type-unsafe, of course.)
Can I do this in Java without copying the three elements' values to an intermediate array?
Sub-question: Are the array elements, being value types, stored at consecutive addresses at all, or is the array composed of elements that are references to integers? Could it be the question does not make sense because even if the answer to the latter was "yes", I could not build on that since that would be an implementation detail that a Java source must not build upon it? It even cannot -- there is no semantics for it, right?
Edit: Stupid index error
You can use List instead of an array.
int[] myValues = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> myValuesList = Arrays.asList(myValues);
// change the argument of function to List
doSomething(List<Integer> input);
// and then just give the function a range of the myValues.
// This List is still backed by your array myValues, it just
// a view of the original array.
doSomething(myValuesList.subList(2,3));
You cannot return a range/subset of items in arrays (also Collection) without creating a new instance of the container.
I cannot answer the second without guessing, but IF the JVM wants to allocate 2 regions of memory for one array, it can do it without you knowing.
In C/C++ this would be terribly easy to do with a bit of pointer arithmetic, but in Java, I am not so sure it is possible.
The best you could do is use the copyOfRange method although that makes a deep copy.

Categories