提供两种解决办法
方案一
// 两个数组,一个数组a中的元素在另一个数组b中存在,就把A中的这个元素移除,得到新的数组 public static String[] getNewArrByTwoArr(String[] targetArr,String[] sourceArr){ List<String> newList = new LinkedList<>(); List<String> sourceList = Arrays.asList(sourceArr); for (String target : targetArr) { if(!sourceList.contains(target)){ newList.add(target); } } return newList.toArray(new String[newList.size()]); } public static void main(String[] args) { String[] a = new String[]{"dd","ww","cc"}; String[] b = new String[]{"aa","bb","cc"}; String[] newArr = getNewArrByTwoArr(a,b); System.out.println("newArr.length:" + newArr.length); for (String s : newArr) { System.out.println("s:" + s); } }
方案二
// 两个数组,一个数组a中的元素在另一个数组b中存在,就把A中的这个元素移除,得到新的数组 public static String[] getNewDistinctArrByTwoArr(String[] targetArr,String[] sourceArr){ List<String> targetList = new ArrayList(Arrays.asList(targetArr)); List<String> sourceList = new ArrayList(Arrays.asList(sourceArr)); targetList.removeAll(sourceList); return targetList.toArray(new String[targetList.size()]); } public static void main(String[] args) { String[] a = new String[]{"dd","ww","cc"}; String[] b = new String[]{"aa","bb","cc"}; String[] newArr = getNewArrByTwoArr(a,b); String[] newArr2 = getNewDistinctArrByTwoArr(a,b); System.out.println("newArr.length:" + newArr.length); for (String s : newArr) { System.out.println("s:" + s); } System.out.println("newArr.length:" + newArr2.length); for (String s : newArr2) { System.out.println("s:" + s); } }
标签:String,newArr,元素,System,length,数组,移除,new From: https://www.cnblogs.com/zhangliang88/p/16872638.html