【编程】java如何删除数组中的元素?简单几步,让你轻松解决。
1. 打开您的IDE(MyEclipse 10为例),在图示空白区域右键点击选择【New】->【Project】->【java Project】->【Next】
2. 步调二后,设置项目标名称、JRE、默认工程位置->【finish】
3. 新建类文件,如下图所示。设置类名、拜候属性、main函数等如下图所示
4. 在步调三中建立的class文件下,添加如下代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class DeleteArrayElementClass {
public static void main(String[] args) {
String[] ss = new String[10];
ss[0] = "/article/90808022090decfd91c80f8e.html";
ss[1] = "/article/90808022090decfd91c80f8e.html";
ss[2] = "/article/90808022090decfd91c80f8e.html";
ss[3] = "/article/90808022090decfd91c80f8e.html";
ss[4] = "/article/90808022090decfd91c80f8e.html";
ss[5] = "我被删除失落了";
ss[6] = "/article/90808022090decfd91c80f8e.html";
ss[7] = "/article/90808022090decfd91c80f8e.html";
ss[8] = "/article/90808022090decfd91c80f8e.html";
ss[9] = "/article/90808022090decfd91c80f8e.html";
ss = deleteArrayEle(ss, 5);
for (String s : ss) {
System.out.println(s);
}
}
public static String[] deleteArrayEle( String[] arr, int index){
int num = arr.length;
if( num <= index)
{
System.out.println("索引值不准确");return null;
}
List<String> list = Arrays.asList(arr);
List<String> arrList = new ArrayList<String>(list);
String target = arr[index];
Iterator<String> it = arrList.iterator();
while(it.hasNext()){
String x = it.next();
if(x.equals(target)){
it.remove();
}
}
//cvt to arr
String[] res = new String[arrList.size()];
arrList.toArray(res);
return res;
}
}
5. 运行法式如下图所示两种体例:1: 选中项目右键选择【Run as】-》【java application】
2: 点击第二张图的运行按钮-》【步调3中的类文件】
6. 删除数组元素前和删除后的对比图,如下所示
若是您感觉有效,记得鄙人方点击投票、点赞、存眷、留言,小编会按期送上更多的惊喜哦,您的撑持才是小编继续尽力的动力,么么哒。
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!