gpt4 book ai didi

java - 从对象数组中删除对象

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:43 24 4
gpt4 key购买 nike

我正在使用 java 处理对象数组。

我已经完成了添加,它有效。我在实现删除(从数组中)时遇到问题。

对象来自名为 Student 的类,它有一个名称和 ID 作为成员

我的工作:

// delete an object
if (count == 0)
System.out.println("Sorry there are no items in the system");
else {
System.out.print("Please enter the ID of Student you'd like to Delete: ");
String searchID = in.nextLine();
for (int i =1 ; i<count; i++) { // first : search for the object
if (searchID.equalsIgnoreCase(Students[i].getID())) {
System.out.print("Are you sure you want do delete "
+ Students[i].getName()+ " from the System? ");
String ans = in.nextLine();
if (ans.equalsIgnoreCase("no")) { break; }
if (ans.equalsIgnoreCase("yes")) {
Students[i] = Students[Students.length-1];
break;
}
} else {
System.out.println("Sorry, you need to type a valid ID to delete it's object.. ");
}
}

最佳答案

首先我无法理解你的代码的逻辑。您应该在收到用户的 100*2 输入之前检查答案。不管怎样,如果你真的想用简单的java数组来做到这一点,你应该这样做,然后删除空对象。这是一种低效的方法:

    String[] a = {"student1", "student2"};
String[] b = {"strudnt3"};
String[] c = new String[a.length + b.length];
// removing one object
a[1] = null;
// copying both arrays to c
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
// ignore null objects
System.out.println(Arrays.toString(c));

更好的方法是使用ArrayList:您可以轻松地从列表中添加和删除对象。在这里查看 JavaDoc http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

如果你想用ArrayList重写代码:

    // creat an ArrayList of the object
ArrayList<Student> studentList = new ArrayList<Student>();

// then, ask if the user wants to add object
Scanner in = new Scanner (System.in);
System.out.print("Would you like to add an object?");

while (true) {
String ans = in.nextLine();
if (ans.equals("no"))
{
break;
}
// else, create the object and add it to the ArrayList
// you can add the attributes from the constructor
studentList.add(new Student(22, "name"));
}

然后您可以轻松地创建一个迭代器,在列表中执行循环并匹配您想要的任何字段,最后从列表中删除对象:

    if (//find the object) {
studentList.remove(object)
}

另请检查此问题以从 ArrayList 中删除对象: remove an object from a List

关于java - 从对象数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27437454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com