java 删除数组元素与删除重复数组元素的代码
程序员文章站
2023-12-21 09:34:04
删除数组借助于list
复制代码 代码如下:private string[] removepaths(string path, string[] srcpaths) {&...
删除数组借助于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;
}