五款java 刪除數組元素與重複數組執行個體代碼
本文章從網路上收藏了java 刪除數組元素哦,各種刪除數組元素都有自己的方法,這裡不但可以刪除數組元素而還可以重複資料刪除的數組元素執行個體。
package com.lzy;
import java.util.hashset;
import java.util.set;
public class test {
/**
* @param args
*/
public static void main(string[] args) {
// todo auto-generated method stub
string[] str = {"a","c","b","a","b","d"};
set<string> set=new hashset<string>();
for(int i=0;i<str.length;i++){
set.add(str[i]);
}
string[] a = (string[]) set.toarray(new string[set.size()]);
for(int i=0;i<a.length;i++){
system.out.println(a[i]);
}
}
}
刪除數組方法二
package com.akfucc.zhidao;
import java.util.arraylist;
import java.util.collections;
import java.util.iterator;
import java.util.list;
public class p124876743 {
public static void main(string[] args) {
int[] nums = { 1, 2, 3, 3, 3, 3, 4 };
list<integer> numlist = new arraylist<integer>();
for (int i : nums)
numlist.add(i);
system.out.println(numlist);
// 做刪除
iterator<integer> it = numlist.iterator();
int temp = -1;
if (it.hasnext())
temp = it.next();
while (it.hasnext()) {
int i = it.next();
if (i == temp) {
it.remove();
} else {
temp = i;
}
}
system.out.println(numlist);
}
}
java重複資料刪除數組元素三
string[] a={1,2,3,4,5,6,7,8,9};
string[] b={1,3,6};
for(int i;i<b.length;i++){
a.remove(b[i]);//其實沒有remove方法,我就不轉型了
}
return a;
方法四
string[] filter(){
arraylist a=new arraylist();
for(int i=0;i<a.length;i++){
boolean find=false;
for(int j=0;j<b.length;j++){
if(a[i].equals(b[j])){
find=true;
break;
}
}
if(false==find)
a.add(a[i]);
}
return a.toarray(new string[]{})
}
方法五
public class test {
public static void main(string[] args) {
string[] a = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
int[] b = { 0, 3, 6 };// 可能會變化
// 怎麼移除a[1和3和6]中的元素變為a={1,3,5,6,8,9...}
string[] a0 = new string[a.length - b.length];
int currentindex = 0;
for (int i = 0; i < b.length; i++) {
for (int j = (i == 0 ? 0 : b[i - 1] + 1); j < b[i]; j++) {
a0[currentindex++] = a[j];
}
p(a0);
}
for (int i = b[b.length - 1] + 1; i < a.length; i++) {
a0[currentindex++] = a[i];
}
p(a0);
}
private static void p(string[] ss) {
for (string s : ss) {
system.out.print(s + "t");
}
system.out.println();
}
}