java 删除数组元素与删除重复数组元素的代码
删除数组借助于list
private String[] removePaths(String path, String[] srcpaths) {
List<String> list = new ArrayList<String>();
int k = srcpaths.length;//原字符串长度
int i=0;
while(i<k){
if(!srcpaths[i].equals(path)){
list.add(srcpaths[i]); //不等就加入list
}
i++;
}
String[] temp = new String[list.size()];
for(int j=0;j<list.size();j++){
temp[j] = list.get(j);
}
return temp;
}
没编译器,随便写写,大概就那个意思吧。。。
private String[] removePaths(String path, String[] srcpaths) {
List list = Arrays.asList(srcpaths);
list.remove(path);
String[] temp = new String[list.size()];
return list.toArray(temp);
}
删除数组中相同的元素
先把源数组进行默认排序
使相同元素相邻
然后进行循环操作删除相同元素
<html>
<body>
<script type="text/javascript">
var source = ["林冲","鲁智深","戴宗","林冲","时迁","朱贵"];
var target = new Array();
source.sort();
target.push(source[0]);
for(var i=1;i<source.length;i++)
{
if(source[i] != source[i-1])
{
target.push(source[i]);
}
}
document.write('原数组:' + source + "<br />");
document.write('所需数组:' + target);
</script>
</body>
</html>
再补充两个实例
public static void main(String[] args) {
getDistinct(new int[] { 6, 7, 3, 6, 5, 2, 7, 8 });
}
static void getDistinct(int array[]) {
java.util.List list = new java.util.ArrayList();
for (int i = 0; i < array.length; i++) {
if (!list.contains(array[i])) {
list.add(array[i]);
System.out.print(array[i] + " ");
}
}
}
输出:6 7 3 5 2 8
看了一下ArrayList的contains()方法源码:
public boolean contains(Object elem) {
return indexOf(elem) >= 0;
}
public int indexOf(Object elem) {
if (elem == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (elem.equals(elementData[i]))
return i;
}
return -1;
}