Удалить элемент массива
Как правильно вывести элементы массива на консоль с учетом удаленного элемента.
public class Remove {
public static void main(String[] args) {
int[] arr = {77, 99, 44, 55, 22, 88, 11 , 0, 66, 33, 10} ;
int count = 0;
int element = 0;
int searchKey;
System.out.println(Arrays.toString(arr));
searchKey = 77;
for (int i = 0; i < arr.length; i++){
if(arr[i] == searchKey){
element = i;
count++;
}
}
for(int j = element; j < arr.length; j++){
arr[j] = arr[j + 1];
}
System.out.println(Arrays.toString(arr));
}
}
Ответы (2 шт):
Автор решения: Дмитрий
→ Ссылка
Сначала надо разобраться как корректно удалить элементы из массива, а вывести уже не проблема
import java.util.Arrays;
public class Remove {
public static void main(String[] args) {
int[] arr = {77, 99, 44, 55, 22, 88, 11, 0, 66, 33, 10};
int removeValue=77;
System.out.println(Arrays.toString(arr));
int[] result = removeByIndex(arr, removeValue);
System.out.println(Arrays.toString(result));
}
public static int[] removeByIndex(int[] array, int value) {
return Arrays.stream(array)
.filter(i->i!=value)
.toArray();
}
}
Без стримов есть несколько вариантов, но это в любом случае менее рационально:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Remove {
public static void main(String[] args) {
int[] arr = {77, 99, 44, 55, 22, 88, 11, 0, 66, 33, 10};
System.out.println(Arrays.toString(arr));
System.out.println(removeByIndex(arr, 99));
}
public static List <Integer> removeByIndex(int [] array, int value) {
List <Integer> list = new ArrayList<>();
for (int element : array) {
if (element!=value) list.add(element);
}
return list;
}
}
Автор решения: doodocina
→ Ссылка
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int[] arr = {77, 99, 44, 55, 22, 88, 11, 0, 66, 33, 10};
arr = removeValue(arr, 77);
System.out.println(Arrays.toString(arr));
}
public static int[] removeValue(int[] array, int value)
{
int[] result = new int[array.length -1];
int c = 0;
for(int i = 0; i < array.length; i++)
{
if(array[i] != value)
{
result[c] = array[i];
c++;
}
}
return result;
}
}
Вот вариант без листов, если Вам так будет удобнее.