简体   繁体   中英

How to remove from an array without using the classes Arrays, Collections, Set, or Map?

test[0] = "one";
test[1] = "two";
test[2] = "one";
test[3] = "three";

I want to remove all the occurrences of "one" but can't use the classes Arrays, Collections, Set, or Map. Thats why I'm stuck, if it wasn't for the restriction I would be able to remove them.

You could have a method like so:

public static String[] removeFromArray(String[] inputArray, String removeString) {
    int removeStringOccurences = 0;
    for (String currString : inputArray) {
        if (currString.equals(removeString)) {
            removeStringOccurences++;
        }
    }
    String[] result = new String[inputArray.length - removeStringOccurences];
    int index = 0;
    for (String currString : inputArray) {
        if (!currString.equals(removeString)) {
            result[index] = currString;
            index++;
        }
    }
    return result;
}

This first checks to see how many times the String we want to remove occurs and then creates a new String[] based on the length of the original String[] minus the times the undesired String occurs.

Running the following:

    String[] test = new String[]{"one", "two", "one", "three"};

    System.out.println("Before:");
    System.out.println(Arrays.toString(test));

    test = removeFromArray(test, "one"); //Call our method

    System.out.println("\nAfter:");
    System.out.println(Arrays.toString(test));

Results in:

Before:
[one, two, one, three]

After:
[two, three]

I think the most appropriate way of solving your issue is to take all of the elements after the element, you want to remove, and shift them one to the front. But this would leave a trail of one unused element.
You could also create a new array without the element to remove.

public void removeFromArrayShift(Object[] arr,int index) {
    for(int i = 0;i< arr.length -1;i++){
         if(i >= index)
             arr[i]=arr[i+1];
    }
    arr[arr.length-1]=null;
}

public Object[] removeFromArrayNew(Object[] arr, int index) {
    Object[] n = new Object[arr.length - 1];
    for(int i = 0; i < n.length;i++) 
        if(i>= index)
            n[i] = arr[i+1];
        else
            n[i] = arr[i];
    return n
}

The later could be optimized with System.arrayCopy if you can access that. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM