Adding to an already set/filled array - java

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

Related

Pass array by reference from a certain index on

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.

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();

Weird output from array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I've come across what appears to be an interesting bug...
For one of my classes, I need to write a program that simulates the old "x students going down a hallway closing lockers every x interval" scenario. However, an interesting twist is that the question requires there to be an equal number of students and lockers up to 100. So I decided to use an array, where the user input a number - which is then used to set up the array size, for-loop conditions, etc. etc... you get the picture, right?
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
Someone (in another thread/question/whatever-you-call-it) stated that this is the physical location of the array in the system memory, and to get the actual numbers from the array the .getNums() method would be required. My problem is: the .getNums() method doesn't seem to exist in Java (perhaps it's part of another language?), so what is the next best alternative or solution?
You're printing out the int array, and that's a traditional array's .toString() representation. You may want to use Arrays.toString() for nicer looking output instead.
To print the content of an array either iterate over each element in the array:
int[] array = new int[10];
for(int s : array) System.out.println(s);
// or
for(int i = 0; i < array.length; i++) System.out.println(array[i]);
or use Arrays.toString():
int[] array = new int[10];
System.out.println(Arrays.toString(array));
which will print something like:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Anyway, my code compiles, but when run it puts out something like:
[I#36ae2282
I assume you are trying to print the array like this:
int[] array = new int[10];
System.out.println(array);
array is an object, hence you are calling println(Object) of PrintStream (System.out), which calls toString() on the passed object internally. The array's toString() is similar to Object's toString():
getClass().getName() + "#" + Integer.toHexString(hashCode());
So the output would be something like:
[I#756a7c99
where [ represnts the depth of the array, and I refers to int. 756a7c99 is the value returned from hashCode() as a hex number.
Read also Class.getName() JavaDoc.

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.

how to make an array in java without length?

I am making an algorithm to save a path of zeroes between 0 1 array
the length of the path will be variable and so i need an array without predefined length
You cannot use array without specifying its length. Consider using ArrayList instead.
You can use an ArrayList which can be between 0 and around 2 billion in lengths.
If you use using a values or 0 and 1, a BitSet may be more efficient.
You can use:
ArrayList<Integer> al = new ArrayList<Integer>();
Note if you wanted to sort this array (for example in ascending order) - you would NOT use
Arrays.Sort(al);
You WOULD use:
Collections.Sort(al);
Use ArrayList instead. An ordinary array cannot be resized so easily - you would have to create a new one of a bigger size and copy the old one into it - I would not recommend this.
ArrayList al = new ArrayList();
al.add(0);
al.add(1);
You can always create array dynamically, e.g. new int[n] where n contains the array length at this moment (not pre-defined at compile time).
But array size cannot be changed. If you need this you should use List instead:
List<Integer> list = new ArrayList<Integer>();
Now you can add and remove elements when you need and the list size will be changed dynamically: you do not have to care about it:
list.add(123);
list.remove(456);
Use ArrayList for a dynamic size.
you can use ArrayList<Boolean> or ArrayList<Integer> and just use the add method. Then utilise the utility methods to get an array out when you are finished constructing the path.
String myArray[] = new Sting[YourVariable];
If speed is a real issue... and you need a dynamically changing array, you could try the following:
// this only works for increasing array-size
int[] tmp = new int[new_bigger_size]; // create a new array
System.arraycopy(array, 0, tmp, 0, array.length); // copy the data
int nextPosition = array.length
array = tmp; // assign the reference
// from position array.length (nextPosition), the new elements can be copied,
// for example:
array[nextPosition] = 120;
....
NOTE! This is very C-ish and not ideal. It is also more difficult to maintain uses more memory during the resizing and is regarded as bad form. Only try this as a last resort and if an ArrayList is really not working for you in terms of speed.
Having said that, does someone have an idea of how much slower (if any) an ArrayList will be?

Categories