Rog Matthews
Rog Matthews

Reputation: 3247

Remove some part of an array in Java

There is an array lut_addresses[] of type int. There are some calculations for a variable table_ptr which is also an int and represents the new base of the array. Now i want to assign lut_addresses[] values beginning from the index table_ptr till the last index to the array lut_addresses[] so that initial values till table_ptr are deleted and value at table_ptr is present at 0th index of lut_addresses[]. How can i do it without changing lut_addresses to an arraylist?

Pseudo code:

A()
{
   int lut_addresses[] = new int[2048];
   // assign values upto a cetain index
   B(lut_addresses);
};
B()
{
   int table_ptr=0;
   //calculate table_ptr;
   // assign lut_addresses[] values from index table_ptr till (lut_addresses.length-1)  
}  

Upvotes: 1

Views: 2194

Answers (7)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

You could either

  • Use a for loop that runs over the desired indices, assigning the elements one at a time, or
  • Use the System.arraycopy method, which copies a given number of elements starting at a given offset in one array to a given offset in another array.

Based on your later edits, I should point out that System.arraycopy correctly handles overlapping source and destination regions, making it an excellent choice for you.

Upvotes: 1

kundan bora
kundan bora

Reputation: 3889

There is no direct method to directly get the specified element as in ArrayList, so you have to first loop to search element and then replace each element after this with (index -index of searched element).

Upvotes: 0

Julien
Julien

Reputation: 1318

I think you could use an IntBuffer. from the documentation :

Relative bulk put methods that transfer contiguous sequences of ints from an int array or some other int buffer into this buffer

Upvotes: 0

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

You can't change an array's size once it's allocated, but you can store in a variable the size of the "used" part (this is close to what ArrayList does internally). So, you could use System.arraycopy() to copy some part of one array into other and use a new int variable to store the size of the filled in part. Then, when you iterate, use that variable instead of lut_addresses.length as the upper iteration limit.

Upvotes: 0

npinti
npinti

Reputation: 52185

First thing that comes to mind would be to use System.arraycopy.

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

Upvotes: 4

AlexZam
AlexZam

Reputation: 1196

for (int i = startIndex; i < 2048; i++) {
  lut_addresses[i] = newValue;
}

Upvotes: 1

Related Questions