我有两个不同的 ArrayList
实例,一个是 Container
类型,另一个是 String
类型。第一个是一个国家的“禁运 cargo ”(字符串)列表,另一个是船上的容器列表。该船穿越该国,并检查容器中是否有违禁 cargo 。如果容器含有
违禁元素,则应移除/删除该容器。
public Customs(String country)
{
countryName = country;
bannedGoods = new ArrayList<String>();
}
public Ship(String n, double weight)
{
emptyWeight = totalWeight = weight;
name = n;
containers = new ArrayList<Container>();
}
我已经在 Ship 类中有一个方法来删除容器:
public void removeContainer(int i)
{
if(i >= 0 && i < containers.size()) {
Container r = containers.remove(i);
totalWeight = totalWeight - r.getWeight();
}
}
我正在尝试创建一种方法来检查
船上的容器。我想对每个数组使用两个 for 循环,但我似乎无法正确执行!有人可以帮我使用两个循环来搜索数组吗?此外,我认为我需要在循环中使用迭代器(特别是 remove
函数),但这也让我感到困惑。迭代器 remove
方法是否应该替换我已经在类 Ship 中编写的方法?这是我所拥有的:
public void inspect(Ship ship)
{
for (String good : bannedGoods) {
for (String con : containers) {
if (con.contains(good) {
container.remove();
}
}
}
这是我对迭代器的尝试:
for(String good : bannedGoods) {
Iterator<String> it = ship.containers.iterator();
while (it.hasNext())
if (ship.contains(good))
it.remove();
}
最佳答案
我认为你不需要 2 个 for 循环。您应该遍历违禁元素并简单地将其从容器中取出。
此外,假设 containers
列表的类型为 string
,正如您在第一行中提到的那样:我有两个相同类型 String 的不同 arrayList
public void inspect(Ship ship, ArrayList<String> bannedGoods){
if (ship == null || bannedGoods == null || bannedGoods.isEmpty())
return;
for(String good : bannedGoods){
ship.containers.remove(good);
}
}
如果Containers
的类型为Container
,并且它包含一个容器列表(字符串的Arraylist)
,可以通过方法get_containers()
访问,则以下内容将起作用:
public void inspect(Ship ship, ArrayList<String> bannedGoods){
if (ship == null || bannedGoods == null || bannedGoods.isEmpty())
return;
for(String good : bannedGoods){
for(Container container : ship.containers){
container.get_containers().remove(good);
}
}
}
关于java - 在 ArrayList 中搜索另一个 ArrayList 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810079/