Trying to print an array - java

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
}
}

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!)

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!

for(String s: restaurentOrders){
if(s.equalsIgnoreCase()){
//You have it..
}
}
If u are storing your array/Arraylist in restaurentOrders. Hope it helps

Related

Creating an arraylist of nulls and then setting the index to an object

Really need help with this as a Patient is not getting set to replace the null. We have to create an arraylist of 50 nulls so the iterator goes through the list and if it finds a null it will set it to the patient. The problem is no patients are getting set to the null. We have to return the bed number at the end too.
protected int amountOfBeds = 50;
ArrayList<Patient> bedList = new ArrayList<Patient>(amountOfBeds);
public int admitPatient(Patient illPatient) {
int index = -1;
if(illPatient.getAge() > 0 && amountOfBeds > size()) {
//if it is null then set to patient
//if it not null then we assume its a patient so we skip
Iterator<Patient> itr = bedList.iterator();
try{
while(itr.hasNext()) {
int bedIndex = bedList.indexOf(itr.next());
if(bedList.get(bedIndex).equals(null)) {
bedList.set(bedIndex, illPatient);
index = bedIndex +1;
break;
}
}
}catch(NullPointerException e) {
e.getMessage();
}
}
return index;
}
Simple way to create 50 nulls list is this
List<Patient> list = Collections.nCopies(50, null);
quick way to find index of null is this
int i = list.indexOf(null);
In Java, an ArrayList is basically an array, that can change its size during execution time. Since you seem to have a fixed amound of beds, an array would probably be better here.
The constructor new ArrayList(50) doesn't create an ArrayList with 50 elements. It creates an empty ArrayList, but gives Java the "hint, that there will probably be inserted 50 elements into the ArrayList. If you don't give such a hint, the ArrayList starts with little space and is periodically made bigger, if it gets too small too accomodate all items you want to insert. This takes time, so if you already know how many items you will insert (even if you only know it approximately) this constructor makes your code faster.
However, you have to think if you really need to do this the way you just wanted to do. Whouldn't it be easier, to just have an empty ArrayList, to which you can add or delete elements just as you want to (without a complicated logic, which replaces null with an element. You could then just add if (array.size() >= 50) // it is full, so some special case may be needed here to make sure there are never more elements in the array than you want.

Java: Recursively Finding the minimum element in a list

I will preface this by saying it is homework. I am just looking for some pointers. I have been racking my brain with this one, and for the life of me i am just not getting it. We are asked to find the minimum element in a list. I know i need a sublist in here, but after that i am not sure. any pointers would be great. thanks.
/** Find the minimum element in a list.
*
* #param t a list of integers
*
* #return the minimum element in the list
*/
public static int min(List<Integer> t) {
if (t.size() == 1){
return t.get(0);
}
else{
List<Integer> u = t.subList(1, t.size());
The point of a recursive algorithm is that everything that must be computed is done through return values or additional parameters. You shouldn't have anything outside the local call of the recursive step.
Since you have to find the minimum element you should take some considerations:
the min element of a list composed by one element is that element
the min element of a generic list is the minimum between the first element and the minimum of the remaining list
By taking these into consideration it should be easy to implement. Especially because recursive algorithms have the convenience of being really similar to their algorithmic description.
You need to find the relationship between the function min applied to a list and the function min applied to a sublist.
min([a b c d e ...]) = f(a, min([b c d e ...]))
Now you just need to find the function f. Once you have the relationship, then to implement it is easy. Good luck.
In the most general sense, recursion is a concept based on breaking down work, and then delegating the smaller chunk of work to a copy of yourself. For recursion to work, you need three main things:
The breakdown of work. How are you going to make each step "simpler"?
The recursive call. At some point your function must call itself, but with less "work".
The base case. What is a (usually trivial) end case that will stop the recursion process?
In your case, you're trying to create a function min that operates on a list. You're correct in thinking that you could somehow reduce (breakdown) your work by making the list one smaller each time (sublist out the first element). As others have mentioned, the idea would be to check the first element (which you just pulled off) against the "rest of the list". Well here's where the leap of faith comes in. At this point, you can "assume" that your min function will work on the sublist, and just make a function call on the sublist (the recursive call). Now you have to make sure all your calls will return (i.e. make sure it will not recurse forever). That's where your base case comes in. If your list is of size 1, the only element is the smallest of the list. No need to call min again, just return (that part you already have in your original post).
/**
* The function computes the minimum item of m (-1 if m is empty).
* #param m: The MyList we want to compute its minimum item.
* #return: The minimum item of MyList
*/
public int minimum(MyList<Integer> m){
int res = 0;
int e0 = 0;
int e1 = 0;
// Scenarios Identification
int scenario = 0;
// Type 1. MyLyst is empty
if(m.length() == 0) {
scenario = 1;
}else {
// Type 2. MyLyst is not empty
scenario = 2;
}
// Scenario Implementation
switch(scenario) {
// If MyLyst is empty
case 1:
res = -1;
break;
// If there is 1 or more elements
case 2:
//1. Get and store first element of array
e0 = m.getElement(0);
//2. We remove the first element from MyList we just checked
m.removeElement(0);
//3. We recursively solve the smaller problem
e1 = minimum(m);
//4. Compare and store results
if(e0 < e1) {
res = e0;
}
else {
res = e1;
}
//5. Return removed element back to the array
m.addElement(0, e0);
break;
}
//6. Return result
return res;
}
There you go, Try this out in the method:
public static Integer minimum(List<Integer> t) {
int minInt;
if (t.size() == 1) {
return t.get(0);
} else {
int first = t.get(0);
List<Integer> u = t.subList(1, t.size());
minInt = Math.min(first, u.get(0));
minInt = IntegerList.minimum(u);
}
return minInt;
}
Hopefully this solves your issue.

Java - ArrayList default initial values

When you create an arraylist of type Integer in Java what are the default values? I need to check if an arraylist is full and I was going to get the size of the array then get the value at the last index and check if it was the default value.
Is there a better way? What would be the default value?
Hope that makes sense. Cheers
int size = a.size();
int last = a.get(size);
if( last == null )
{
return true;
}else{
return false;
}
Edit;
Is it possible to create an ArrayList with a max size that you can not go over to stop it dynamically expanding?
When you create an ArrayList and you use size() would that return the actual size or the amount of elements in the arraylist?
When doing this to create a max size would the default values be null?
public boolean isFull()
{
int size = a.size();
int last = 0;
try{
last = a.get(size-1);
}catch (Exception e){
}
if( last == null )
{
return true;
}else{
return false;
}
}
I currently have this, how does it look? Does this make sense now?
When you declare an ArrayList it is empty. It is also a dynamic container meaning it will grow so for you to ask if it is "full" is more of a constraint you'd need to add to your code.
So, if you want to achieve a goal like you describe.
List<Integer> list = new ArrayList<Integer>();
int MAX_ELEMENTS = 5; //Set this to however you want to constrain the datatype
public boolean addElement(Integer value) {
if (list.size() < MAX_ELEMENTS) {
list.add(value);
return true;
} else {
return false;
}
}
public boolean isFull() {
return (list.size() == MAX_ELEMENTS);
}
public Integer getLast() {
if (!list.isEmpty())
return list.get(list.size()-1);
else
return null;
}
As others have stated though, if you generate a list with a preset size as such:
List<Integer> list = new ArrayList<Integer>(10);
You'd have a list of 10 elements large all being null in value. Should you add additional elements the list will still grow larger than 10 elements unless you constrain it like I did above.
If you haven't actually added Integers to the ArrayList, then any get() on the list will return an IndexOutOfBoundsException.
The size() method returns the number of elements in the list (i.e. how many you have added to it), not the current capacity.
By default ArrayList capacity is 10. All of them are null by default until you add your elements into it. But calling size() will give you number of elements that you have added. It wont give 10 as result(default null values will not be considered). Twist here is if you add null values to the list then they are included while calculating size(). Example if you add 3 valid Integers and 2 null values into the list then size() will return 5. Eclipse debugging will help you in finding this dynamic increasing of its capacity.
When you create an ArrayList, inside the ArrayList class, there is an array of elements. Those elements are set to null because they do not refer to any instance of an Integer object. Bare in mind, that isn't the same as an int.
Moreover, an ArrayList doesn't get full. It is dynamic, and will increase in size when it needs to.
Edit: in response to your edit about setting a maximum size, if you want a maximum size then I'm not sure why you'd want an arraylist. But if you want to stick with an ArrayList class, I would create my own class that is a subclass of arraylist, and override the add method with a check to ensure the value of size() isn't over a fixed amount.
There is not such thing like "full" ArrayList. The size() method will return the number of elements it currently holds.
Do you want to simply constraint the list to a given size, or do you want to check if it is larger than a given size?
Check if list is larger than:
if (list.size() > limit)
System.out.println("List too large");
Its not possible to constraint the size of an ArrayList - you can however create your own subclass of ArrayList that does just that:
public class LimitedList<E> extends ArrayList<E> {
private int limit;
public LimitedList(int limit) {
this.limit = limit;
}
public boolean add(E e) {
// only add if the limit is not exceeded
if (size() < limit)
super.add(e);
}
// overwriting the addAll()-methods is left as an excercise to the reader
}
You only need to decide what the list should DO when one attempts to add more elements than the limit allows. Either just ignore the elements or throw an Exception.
ArrayLists have no default values. If you give the ArrayList a initialCapacity at initialization, you're just giving a hint for the size of the underlying array—but you can't actually access the values in the ArrayList until you add the items yourself.
Any List implementation has a isEmpty() method you can use.

Better way to find index of item in ArrayList?

For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
Use indexOf() method to find first occurrence of the element in the collection.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2

Java ArrayList replace at specific index

I need help with this java please. I created an ArrayList of bulbs, and I'm trying to replace a bulb at specific index with another bulb. So with the following heading, how do I proceed?
public void replaceBulb(int index, Bulbs theBulb) {
}
Check out the set(int index, E element) method in the List interface
You can replace the items at specific position using set method of ArrayList as below:
list.set( your_index, your_item );
But the element should be present at the index you are passing inside set() method else it will throw exception.
Also you can check oracle doc here
Use the set() method: see doc
arraylist.set(index,newvalue);
Use ArrayList.set
public void setItem(List<Item> dataEntity, Item item) {
int itemIndex = dataEntity.indexOf(item);
if (itemIndex != -1) {
dataEntity.set(itemIndex, item);
}
}
Lets get array list as ArrayList and new value as value
all you need to do is pass the parameters to .set method.
ArrayList.set(index,value)
Ex -
ArrayList.set(10,"new value or object")

Categories