从字符串数组中删除特定字符串
我有一个像这样的数组:
String n[] = {"google","microsoft","apple"};
我想要做的是删除“苹果”。
我的问题是非常基本的,然而,我搜索了网站,我发现java并不真正支持数组中的删除function。我也听说过使用Java Utils,因为删除项目非常简单….我试图在谷歌上找到Java Utils,但几乎所有的链接都已经死了。
所以最后……有没有办法从字符串数组中删除一个字符串?
即使我使用ArrayList,我也找不到生成随机项的方法! 例如:在普通数组中,我生成一个这样的字符串:
String r = myAL[rgenerator.nextInt(myAL.length)];
在arraylist它不起作用….也许你知道一个解决方案……
定义“删除”。
数组是固定长度的,一旦创建就无法resize。 您可以将元素设置为null
以删除对象引用;
for (int i = 0; i < myStringArray.length(); i++) { if (myStringArray[i].equals(stringToRemove)) { myStringArray[i] = null; break; } }
要么
myStringArray[indexOfStringToRemove] = null;
如果您想要一个动态大小的数组,其中实际删除了对象并相应地调整了列表(数组)大小,请使用ArrayList
myArrayList.remove(stringToRemove);
要么
myArrayList.remove(indexOfStringToRemove);
编辑以回应OP对他的问题和评论的编辑
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
在步骤中不可能或者您需要保持对数组的引用。 如果您可以更改参考,这可以帮助:
String[] n = new String[]{"google","microsoft","apple"}; final List list = new ArrayList (); Collections.addAll(list, n); list.remove("apple"); n = list.toArray(new String[list.size()]);
我不推荐以下内容,但如果您担心性能:
String[] n = new String[]{"google","microsoft","apple"}; final String[] n2 = new String[2]; System.arraycopy(n, 0, n2, 0, n2.length); for (int i = 0, j = 0; i < n.length; i++) { if (!n[i].equals("apple")) { n2[j] = n[i]; j++; } }
我不推荐它,因为代码更难以阅读和维护。
Java中的数组不是动态的,就像集合类一样。 如果您想要一个支持动态添加和删除的真集合,请使用ArrayList <>。 如果您仍想使用vanilla数组,请找到string的索引,构造一个大小比原始数组小的新数组,并使用System.arraycopy()
复制前后的元素。 或者手动编写一个副本循环,在小数组上差异可以忽略不计。
你不能从数组中删除任何东西 – 它们总是固定长度。 一旦创建了长度为3的数组,该数组的长度始终为3。
你最好使用List
,例如ArrayList
:
List list = new ArrayList (); list.add("google"); list.add("microsoft"); list.add("apple"); System.out.println(list.size()); // 3 list.remove("apple"); System.out.println(list.size()); // 2
像这样的集合通常比直接使用数组更灵活。
编辑:删除:
void removeRandomElement(List> list, Random random) { int index = random.nextInt(list.size()); list.remove(index); }
import java.util.*; class Array { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("google"); al.add("microsoft"); al.add("apple"); System.out.println(al); //i only remove the apple// al.remove(2); System.out.println(al); } }