How to insert a series of elements in an array
The current code to insert one element in an array is as follows:
public static void getArrayElement()
{
try
{
if(initialSize==1)
{
//Get the user input
System.out.print("Enter the element: ");
getElement = key.nextInt();
//Assign the user input to the array
for(int i=0; i<index; i++)
{
array[i] = getElement;
}
}
//If the size of the array is not 1 use this
else
{
//Gets the user input
System.out.print("Enter the element: ");
getElement = key.nextInt();
//Create a new empty array with a new size
int[] temp = new int[index];
//Assign the old array into the new array
for(int j = 0; j < index-1; j++)
{
temp[j] = array[j];
}
//Change the size of the old array
array = new int [index];
//Assign the temporary array into the new array with its new size
for(int aSize = 0; aSize< array.length; aSize++)
{
array[aSize] = temp[aSize];
int k = array.length;
array[k-1] = getElement;
}
//Pass the array into sortArray method for sorting
sortArray(array, index);
}
//Increment the index and initialSize
index++;
initialSize++;
}
catch(InputMismatchException e)
{
System.out.println("Invalid Input");
System.exit(0);
}
}
As you see the above code can insert only one element at a time. But if I want to insert a bunch of elements at a time, How do i do that ?
Before finding an answer it is better to understand what arrays are.
Array is a set a of homogeneous elements stored in a contiguous memory
location.
This makes a limitation that Arrays need to know the size when they are initialized to reserve enough space from the memory. This makes insertion not possible at all in the parent array. For that you will have to do an arraycopy or create a new array with a different size.
For example,
int[] array = new int[10]; //Initializes an integer array of size 10.
for(int i=0;i<10;i++){
array[i] = i;
}//stores values from 0 to 9.
Now if you intend to insert one or 'n' elements at the start, you have to either create a new array with size "size of prev array + 1" or "size of prev array + n" respectively. And perform an array copy followed by an insertion at the start.
So, if you want a dynamic object doing this for you (inserting one, inserting in bulk), you will have to define your custom capacity that the array can hold. And then you will have to increase the capacity based on your preference.
Developing on this problem, you will reinvent the Java's ArrayList. So better use it in your case.
If key is a Scanner you could just do this:
while( key.hasNextInt() ) {
int i = key.nextInt();
//do with i whatever you want
}
I'd also suggest using a list instead of an array. Then just pass the list to Collections.sort(list) to keep it sorted.
Although lists only allow you to add objects you could make use of autoboxing and convert an int to Integer upon inserting.
Alternatively there are libraries that support primitive lists out there - Google Guava and Apache Commons, for example, should provide some.
Another alternative might be sorted collections like Apache Common's TreeBag which allows you to add multiple duplicate items into a sorted structure.
You want to copy content of temp into array. You can achieve this in one at most two steps
if (temp.length > array.length)
array = new int[temp.length];
System.arraycopy(temp, 0, array, 0, temp.length) ;
Related
I have a problem with one of our old exam tasks.
the task is
"the method positions should return a field containing exactly the positions of those elements of the list that have null as content. if there are no such elements than return a field with the length 0"
the code starts with :
public int[] positions() {
int[] result = new int[0];
I keep getting stuck on because of the "new int[0]" when I tried solving the problem without it I managed to get somewhat of a result. but I don't know how to do it with this part.
Just think for a moment what the code is doing here.
int[] result = new int[0];
creates an empty, fixed lenght, primitive array. This array cannot be further expanded.
Your exam task would be translated as (simplifying at a large degree):
public int[] positions(final Object[] objects) {
// Initialize the array with the max possible size, which is the input array size
final int[] positions = new int[objects.lenght];
int j = 0;
for (int i = 0; i < objects.length; i++) {
if (objects[i] == null) {
// Assign the index of the null value to the holder array.
// Increment j, which is the index of the first free position in the holder array
positions[j++] = i;
}
}
// This will return a copy of the "positions" array, truncated at size j
return Array.copyOf(positions, j);
}
Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.
I am working on a homework assignment involving array sorting methods, we are given the methods, and I'm having a little trouble understanding how this insertion sort method functions. More specifically, the role the two variables passed to the method play.
As I understand, the Key variable describes the index of the array that you'd like to place your inserted number in and the item is the number itself. Within main, I simply request the user to enter two numbers and pass them to the method, one for the key and the other for the item. Here is the given code for this segment:
public final void insertion(double Key, double Item)
{
if (arraySize == 0)
{
arr[0] = Item;
}
/* find the position for inserting the given item */
int position = 0;
while (position < arraySize & Key > arr[position])
{
position++;
}
for (int i = arraySize; i > position; i--)
{
arr[i] = arr[i - 1];
}
arr[position] = Item;
arraySize = arraySize + 1;
}
However, when I pass doubles to the method as I have explained, I get an error stating that index (array length) is out of bounds for length (array length).
Clearly, I am misunderstanding the purpose or structure of this method and I can't figure it out. Any help would be appreciated. I know this is a very simple problem.
EDIT: Here is how I initialize my array, the given code is in a separate class from my main method:
public static double[] arr;
private int arraySize;
public sortedArrayAccess(int scale)
{
arr = new double[scale];
arraySize = arr.length;
}
Within my main method:
System.out.print("Enter an array size: ");
int d = sc.nextInt();
sortedArrayAccess test = new sortedArrayAccess(d);
for(int i=0;i<test.arr.length;i++)
{
System.out.print("Enter a number for index " + i + ": ");
double c = sc.nextDouble();
test.arr[i] = c;
}
How do you initialize ‘arr’ variable?
Anyway the problem is that when you create the array - you should specify initial capacity. And every time when you add the element into array you are about to increase it.
When you try to ask for for a cell of array indexed i if array capacity is less then I - you’ll be given the arrayOutOfBoundsException.
Your problem is here:
if (arraySize == 0)
{
arr[0] = Item;
}
You are assigning the Item to the first element in the array. But the array size must be empty as stated by the if (arraySize == 0)
So you have two options:
adjust the size of the array (by creating a new one)
or return an error
if (arraySize == 0)
{
arr[0] = Item;
}
As you know, in computer science, indices starts from 0. Which means arr[0] here is the first slot of your array. if arraySize is 0, there is no such index arr[0]. Your code tries to insert the Item to zero sized array. This causes Index out of bound exception.
By the way, If it is a sorting algorithm for the values, "Key" variable is not required. You can delete it. But if it is required, you should sort the elements by their key values.
For example if we have:
element 1 -> key= 101 , value= 6
element 2 -> key= 201 , value= 9
element 3 -> key= 301 , value= 2
you should not sort them as element 3 < element 1 < element 2
you should sort them like: element 1 < element 2 < element 3 in order to their key values.
In other words, if you want to sort them by their values, passing key values as a parameter is meaningless.
I am trying to populate an array list, however, my array list constantly equals 0, and never initializes, despite my declaring it over main().
This is my code.
static ArrayList<Integer> array = new ArrayList<Integer>(10); //The parenthesis value changes the size of the array.
static Random randomize = new Random(); //This means do not pass 100 elements.
public static void main (String [] args)
{
int tally = 0;
int randInt = 0;
randInt = randomize.nextInt(100); //Now set the random value.
System.out.println(randInt); //Made when randomizing number didn't work.
System.out.println(array.size() + " : Array size");
for (int i = 0; i < array.size(); i++)
{
randInt = randomize.nextInt(100); //Now set the random value.
array.add(randInt);
tally = tally + array.get(i); //add element to the total in the array.
}
//System.out.println(tally);
}
Can someone tell me what is going on? I feel rather silly, I've done ArrayLists for my default arrays and I cannot figure this out to save my life!
new ArrayList<Integer>(10) creates an ArrayList with initial capacity of 10 but the size is still 0 as there are no elements in it.
ArrayList is backed by an array underneath so it does create an array of a given size (initial capacity) when constructing the object so it doesn't need to resize it every time you insert a new entry (arrays in Java are not dynamic so when you want to insert a new record and the array is full you need to create a new one and move all the items, that's an expensive operation) but even though the array is created ahead of time size() will return 0 until you actually add() something to the list.
That's why this loop:
for (int i = 0; i < array.size(); i++) {
// ...
}
Will not execute as array.size() is 0.
Change it to:
for (int i = 0; i < 10; i++)
And it should work.
Let's that I have a number N. N will be the size of the array.
int numArray [] = new numArray[N];
However, the contents of the array will hold every other number from 1 to positive N. This means that the entire size N array will not be full after that for loop. So after the for loop, I want to trim (or resize) the array so that there will no longer be any empty slots in the array.
Example :
Let's say N = 5;
That means, after the for loop, every other number from 1 to 5 will be in the array like so:
int arr[] = new int[N];
int arr[0]=1;
int arr[1]=3;
int arr[2]= null;
int arr[3]= null;
int arr[4]= null;
Now, I want to trim (or resize) after the for loop so that the indexes that hold null will be gone and then the array should be:
int arr[0]=1;
int arr[1]=3;
The size of the array is now 2.
You can't trim an array. The fastest approach is just to copy it into a smaller one, using System.arraycopy, which is almost always much faster than a for loop:
int somesize = 5;
int[] numArray = new int[somesize];
//code to populate every other int into the array.
int[] smallerArray = new int[somesize/2];
//copy array into smaller version
System.arraycopy(numArray, 0, smallerArray, 0, somesize / 2);
You can't change the size of an array in Java after it has been created.
What you can do however, is to create a new array of the size that you need.
Another important point is that you are creating an array of a primitive: int. Primitives are not objects and you cannot assign the value null to a primitive.
You need to create an array of java.lang.Integer if you want to be able to set entries in it to null.
Integer[] numArray = new Integer[N];
Thanks to a Java feature called auto-boxing, almost all code that works with primitive int values, also works with Integer values.
Steps:
Use Integer[] instead of int[]
Calculate the size that you need (count non-null entries in original array)
Allocate a new array of the size that you need
Loop over the old array, and copy every non-null value from it to the new array.
Code:
Integer[] oldArray = ...;
// Step 2
int count = 0;
for (Integer i : oldArray) {
if (i != null) {
count++;
}
}
// Step 3
Integer[] newArray = new Integer[count];
// Step 4
int index = 0;
for (Integer i : oldArray) {
if (i != null) {
newArray[index++] = i;
}
}
I think there is a bit shorter way to do the trimming itself.
Whats left is to find the proper index.
You can do:
int someIndex = Arrays.asList(arr).indexOf(null);
arr = Arrays.copyOfRange(arr,0,someIndex);
You surely better of with some more appropriate data structure, for example a list or a set depending on what's your intention with it later. That way you don't even need to create an N sized structure just so you'd have to reduce it anyway. Rather you create an empty list and add the elements that you actually need
import java.util.Arrays;
public static void main( String[] args )
{
int[] nums2 = {9,4,1,8,4};
nums2 =Arrays.copyOf(nums2,3);
for (int i : nums2) {
System.out.print(i+" ");
}
}
//Output
9 4 1