Array element delete
In this chapter you will learn:
- How to remove duplicate element from array
- Remove the element at the specified position from the specified array.
Remove duplicate element from array
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//from ja v a2s . co m
public class Main {
public static void main(String[] args) {
String[] data = { "A", "C", "B", "D", "A", "B", "E", "D", "B", "C" };
System.out.println("Original: " + Arrays.toString(data));
List<String> list = Arrays.asList(data);
Set<String> set = new HashSet<String>(list);
System.out.print("Remove duplicate result: ");
String[] result = new String[set.size()];
set.toArray(result);
for (String s : result) {
System.out.print(s + ", ");
}
}
}
The code above generates the following result.
Remove the element at the specified position from the specified array.
import java.lang.reflect.Array;
// ja va2 s.c o m
public class Main {
public static short[] remove(short[] array, int index) {
return (short[]) remove((Object) array, index);
}
private static Object remove(Object array, int index) {
int length = getLength(array);
if (index < 0 || index >= length) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
}
Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);
System.arraycopy(array, 0, result, 0, index);
if (index < length - 1) {
System.arraycopy(array, index + 1, result, index, length - index - 1);
}
return result;
}
public static int indexOf(short[] array, short valueToFind) {
if (array == null) {
return -1;
}
for (int i = 0; i < array.length; i++) {
if (valueToFind == array[i]) {
return i;
}
}
return -1;
}
public static int getLength(Object array) {
if (array == null) {
return 0;
}
return Array.getLength(array);
}
public static short[] clone(short[] array) {
if (array == null) {
return null;
}
return (short[]) array.clone();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Array