java 刪除數組元素與刪除反復數組元素的代碼。本站提示廣大學習愛好者:(java 刪除數組元素與刪除反復數組元素的代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是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;
}