Reputation: 41
I need some help with java and returning a result from an array.
My array list stores orders from a restaurant (created by the Order Class). The Deliverylog Class (which creates the array lists) then has a method for adding the orders to an array list called waitingList.
Each order has a reference number aswell ass details of it delivery time and so on ..
What im trying to do , but havent got a clue is to , is to create a method with a parameter (int ref) that will search the array list for an item with the same reference number as the one entered. When it finds it it returns the order , otherwise it returns null.
Any help is appriciated.
code
/**
* Show a order.
* @param refnum The reference number of the order to be shown
*/
public void findOrderWaiting(int refnum)
{
if(refnum < 0) {
// This is not a valid reference number
}
else if(refnum <= numberOfOrders()) {
// This is a valid reference number
System.out.println(waitingList.get(refnum));
}
else {
// This is not a valid reference number
}
}
Upvotes: 1
Views: 88
Reputation: 11926
You know arrayList has a method to find an item inside:
//a is an arraylist
//filling the list here is omitted
//o is the object to find its index
int ind=a.indexOf(o);
int indexOf(Object o)
is already-invented so you dont have to make a method. If you want this for learning purposes, you can search hashing techniques from internet but you are using arrayList and the easiest thing is the indexOf() method.
HashTable is more flexible by giving you freedom to search for an item or a key (you give key and get item or you give item and get its key)(key can be an object too!)
Upvotes: 1
Reputation: 86
for(String s: restaurentOrders){
if(s.equalsIgnoreCase()){
//You have it..
}
}
If u are storing your array/Arraylist in restaurentOrders. Hope it helps
Upvotes: 0
Reputation: 1647
Well, you could loop through the array using a standard for loop:
for(int i=0; i<array.length; i++){
if(array[i].intPart == ref) return array[i];
}
return null;
Hope that helps!
Upvotes: 0