- Java code
public static String deleSubSet() { char[] parent = {'0','1','2','3','4','5','6','7','8','9'}; Arrays.sort(parent); char[] subSet = {'6','3','4',}; Arrays.sort(subSet); StringBuffer sb = new StringBuffer(); for (int i = 0, k = 0; i < parent.length; i++) { if (parent[i] == subSet[k]) { k++; } else { sb.append(parent[i]); } } return sb.toString(); }
作用:将parent中,包含subSet的元素删除,然后返回被删除后的parent
看这个代码有什么问题。
------解决方案--------------------
- Java code
for (int i = 0, k = 0; i < parent.length; i++) { if (k<subSet.length && i<parent.length && parent[i] == subSet[k]) { k++; } else { sb.append(parent[i]); } }
------解决方案--------------------
你的问题在于会把k值增加到大于subSet的范围,引发异常,1楼加上了判断处理,就避免了这个问题,不过1楼if里的i<parent.length这个就没有必要了。
------解决方案--------------------
------解决方案--------------------
- Java code
import java.util.*;public class Del{ public static void main(String[] args) { char[] parent = {'0','1','2','3','4','5','6','7','8','9'}; Arrays.sort(parent); char[] subSet = {'6','3','4',}; Arrays.sort(subSet); StringBuffer sb = new StringBuffer(); for (int i = 0, k = 0; i < parent.length; i++) { if (k<subSet.length && parent[i] == subSet[k]) { k++; } else { sb.append(parent[i]); } } System.out.println(sb); //return sb.toString(); }}
------解决方案--------------------
用API更简单
- Java code
public static String deleSubSet() { Character[] parent = {'0','1','2','3','4','5','6','7','8','9'}; Character[] subSet = {'6','3','4',}; ArrayList<Character> pArrayList = new ArrayList<Character>(); ArrayList<Character> sArrayList = new ArrayList<Character>(); pArrayList.addAll(Arrays.asList(parent)); sArrayList.addAll(Arrays.asList(subSet)); pArrayList.removeAll(sArrayList); return pArrayList.toString(); }
------解决方案--------------------