I have an object and a variable with a reference to its instance must be deleted from the object itself.

as well as remove it from the array with a shift (no holes) elements.

Closed due to the fact that the essence of the question is not clear to the participants in αλεχολυτ , Grundy , iluxa1810 , Denis , HamSter Nov 13 '16 at 6:35 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Explain the first part in a little more detail. The object, generally speaking, is just a link. And an object and an instance (of a class) are one and the same. - post_zeew
  • Punctuation absent - markov

1 answer 1

Removing an element from an array with a shift (no holes) of elements:

public static void removeElt(int [] arr, int remIndex) { for (int i = remIndex ; i < arr.length - 1; i++) { arr[i] = arr[i + 1] ; } } 

But in this case, all the elements you have after the deleted one will move higher, and you need to nullify the last element of the array, or delete the object reference if your array stores references. In the case, if you want to get an array with a smaller length of elements (for example, there was an array {1, 2, 3, 4, 5} , and after removing the element "4" you want to get an array {1, 2, 3, 5} ), then use the following method:

 public static int[] removeElt(int[] arr, int remIndex) { for (int i = remIndex; i < arr.length - 1; i++) { arr[i] = arr[i + 1]; } int[] newArr = new int[arr.length - 1]; System.arraycopy(arr, 0, newArr, 0, arr.length - 1); return newArr; } 

This method returns a new array. An example of its use:

 public static void main(String[] args) { int[] ar = {1, 2, 3, 4, 5}; System.out.println("Исходный массив: "); for (int a : ar) { System.out.print(a + " "); } System.out.println("\nНовый массив: "); int[] newArr = removeElt(ar, 3); for (int a : newArr) { System.out.print(a + " "); } } 

And the conclusion:

Source array: 1 2 3 4 5
New array: 1 2 3 5