从一个数组中删除另一个数组中的值

时间:2018-05-08 03:13:03

标签: java arrays

任何人都知道如何在不使用ArrayList的情况下从一个数组中删除一个数组中的值?我认为之前已经问过,但我只能使用ArrayList找到解决方案。

例如

int[] set01 = {1, 2, 3, 4, 5, 6};
int[] set02 = {1, 2};
int[] set03;

//function to remove set02 from set01, yielding set03
//set03 = {3, 4, 5, 6}

来自实际脚本的摘录:

//just a placeholder, length of 'ptSet' is variable
//these are point coordinates {x, y} - the actual values don't matter
float[][] ptSet = new float[100][2];

//populate ptSet with 100 points

//'set02' of original question
int[] cchOrdered = {1, 12, 22, 32, 54};

//'set03' of original question
int[] eligiblePts = new int[0];

//compare 'cchPts' with 'ptSet'
for (int j = 0; j < ptSet.length; j++) {
  for (int k = 0; k < cchOrdered.length; k++) {
    //this doesn't work, as the nested loop invalidates any duplicate checks
    if (!(cchOrdered[k] == j)){
      eligiblePts = (int[]) append(eligiblePts, j);
    }
  }
}

再次,对不起,如果我的代码不是那么干净......还在这里学习:S

1 个答案:

答案 0 :(得分:0)

最佳解决方案是使用ArrayList。由于您不想使用它,您可以执行以下操作。

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class MyClass {
    public static void main(String args[]) {
        int[] set01 = {1, 2, 3, 4, 5, 6};
        int[] set02 = {1, 2};

        //assume set01 having more elements than set02 array 
        int[] set03 = Arrays.copyOf(set01, set01.length);            

       // sorting array is optional if you know the arrays are sort.
        Arrays.sort(set01);
        Arrays.sort(set02);

        for(int value :set02){
            set03 = ArrayUtils.removeElement(set03, value);          
        }

        for(int value:set03){
           System.out.println("set03 array :"+ value);

        }      
    }
}