Reputation: 297
I want to know how to iterate through the following Arraylist.
public class FruitHandler {
private ArrayList<Fruits> fruit;
private ArrayList<Integer> fruitUID= new ArrayList<>();
public static FruitHandler getInstance() {
return instance;
}
public void addFruit(Fruit fruit) {
this.fruitUID.add(fruit.getfruitUID());
this.fruit.add(fruit);
}
}
What I want to do is to iterate through the fruitUID and return the instance of that fruit class that is stored in ArrayList<Fruits> fruit
which matches my given UID.
Example, I have an fruitUID = 10
, I want to have the reference of the instance of the fruit class that is stored in ArrayList<Fruits> fruit
which have its fruitUID = 10
.
Upvotes: 4
Views: 327
Reputation: 1058
The solution point out by @Jason will make your problem much easier, but if you are in hurry and consider using a quick solution you can have the following code (not good in term of performance
public class FruitHandler {
private ArrayList<Fruits> fruit;
private ArrayList<Integer> fruitUID= new ArrayList<>();
public static FruitHandler getInstance() {
return instance;
}
public void addFruit(Fruit fruit) {
this.fruitUID.add(fruit.getfruitUID());
this.fruit.add(fruit);
}
public Fruit findFruitByFruitUID(Integer fruitUID){
for(Fruit fr: fruit){
if(fr.getfruitUID()==fruitUID){
return fr;
}
}
return null;
}
}
Upvotes: 1
Reputation: 11832
If you want to retrieve a Fruit
instance given a fruitUID then you probably want a Map<Integer, Fruit>
.
You could also just have a list of Fruit
instances and use a stream and a filter to find just the single instance with a specified fruitUID.
If you absolutely must use two lists, then you need find the index of the specified fruitUID and extract the Fruit
from the other list at the same index.
Edit: If you want to use a map:
private Map<Integer, Fruits> fruits = new HashMap<>();
public void addFruit(Fruit fruit) {
fruits.put(fruit.getfruitUID(), fruit);
}
public Fruit findFruit(Integer fruitUID) {
return fruits.get(fruitUID);
}
Upvotes: 5