本文介绍了如何从数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请耐心等待,因为这可能很难理解
Please bear within as it might be difficult to understand
我有一个大小为50的jbutton数组,在本例中,我滥用7我在1 2 3 4 6 7内拥有jbutton对象,但在5之内.这些都打印在屏幕上.我想删除这些jbutton,但是最多删除5个所有按钮,而最后两个没有删除.
I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not.
for(int i = 1; i < 51; i++){
if(seat.buttonArray[i] == null){
remove(seat.buttonArray[i]);
seat.buttonArray[i] = null;}
}
推荐答案
无法从array
中删除元素,假设您希望在删除后更改后一个索引.为此,您应该使用List
:
There is no way to remove element from array
, assuming you want latter indexes changed after remove. For this purpose, you should use List
:
Iterator buttonIterator = seat.buttonList.iterator();
while (buttonIterator.hasNext()) {
Object button = buttonIterator.next(); //or more specific type, if your list was generified
if (button == null) { //or some other criteria, wrote this just as an example
buttonIterator.remove();
}
}
如果必须使用array
,则有两个选择:
If using array
is mandatory, you have two options:
- 将
seat.buttonArray[i]
设置为null
值,表示已将其删除; - 每次删除某些内容时都重新创建数组.请参见 System.arraycopy javadoc以获得详细信息,尽管出于性能考虑,我不建议使用此方法.
- Set
seat.buttonArray[i]
tonull
value, indicating it has been removed; - Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
这篇关于如何从数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!