我试图从数组中删除一个元素,具体取决于方法的参数。如果参数是最后一个元素的位置,我不能使用for循环并最终指定if语句来满足该条件。还试图在删除后返回该位置的当前名称。我已经测试过以下代码。
我试图看看是否有更好的方法来产生相同的结果而没有额外的if语句。我尝试查找Arrays类,没有静态方法,似乎也有帮助。如果有更好的方法来做这种方法,请建议。谢谢。
public class ArrayTester {
public static String[] array1 = new String[100];
public static void main(String[] args) {
remove(50);
System.out.println(remove(50));
}
public static String remove(int name) {
if(name == 99){
array1[name] = null;
return array1[name];
}
else if (name >= 0 && name < 99){
for (int i=name; i < array1.length-1; i++){
array1[i] = array1[i+1];
}
return array1[name];
}
return null;
}
}
答案 0 :(得分:1)
并使用ArrayList ??
import java.util.ArrayList;
public class RemoveArrayListElement {
public static void main(String[] args) {
ArrayList<String> arlist=new ArrayList<String>();
//<E> it is return type of ArrayList
arlist.add("First Element"); // adding element in ArrayList
arlist.add("Second Element");
arlist.add("Third Element");
arlist.add("forth Element");
arlist.add("fifth Element");
// remove array list element by index number
arlist.remove(3);
// remove ArrayList element by Object value
arlist.remove("fifth Element");
// get elements of ArrayList
for(int i=0;i<arlist.size();i++)
{
System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
}
}
}
输出:
Remove ArrayList Element 0 :First Element
Remove ArrayList Element 1 :Second Element
Remove ArrayList Element 2 :Third Element
使用ArrayList更容易,不是吗?
答案 1 :(得分:0)
看看你的代码,你似乎想要这样的东西 -
if (name == 99) {
try {
return array1[name];
} finally {
array1[name] = null;
}
}
答案 2 :(得分:0)
array1 = Arrays.copyOf(array1, 99);
答案 3 :(得分:0)
您可以通过排除if
来简化代码。不幸的是,循环必须保持 - 数组提供连续的存储,因此如果要删除数组中间的项目,则需要移动数据。
public static String remove(int index) {
// Note the use of "index" instead of "name"
if (index < 0 || index >= array1.length) {
// A more common approach is to throw an exception,
// but your code returns null for out-of-range index
return null;
}
for (int i = index; i < array1.length-1 ; i++) {
array1[i] = array1[i+1];
}
// Unconditionally set null in the last element of the array
array1[array1.length-1] = null;
return array1[index];
}
答案 4 :(得分:0)
听起来像你最好使用ArrayList。数组并不是真正适用于你正在做的事情。但您也可以在所需位置取消该值,并在阵列上运行java.util.Arrays.sort方法。像这样的东西(我正在wing,但这会很接近):
public static String remove(int name) {
String returnValue = array1[name];
array1[name] = null;
java.util.Arrays.sort(array1);
return returnValue;
}
这将为您留下一个已排序的数组,但您已经将它们从原始索引中移出,因此对您来说可能或不重要。
另一个选择是简单地为处理该数组的所有代码添加if (array1[index] != null)
条件。这样你就不必在数组中改变你的值,你的代码就会跳过它遇到的任何空值。