Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A <code>while</code> applies to the expression or block after the <code>while</code>.</p> <p>You dont have a block, so your while ends with the expression <code>dog=al.get(i);</code></p> <pre><code>while(dog.getId()!=id &amp;&amp; i&lt;length) dog=al.get(i); </code></pre> <p>Everything after that happens only once.</p> <p>There's no reason to new up a Dog, as you're never using the dog you new'd up; you immediately assign a Dog from the array to your dog reference.</p> <p>And if you need to get a value for a key, you should use a Map, not an Array.</p> <p>Edit: this was donwmodded why??</p> <p>Comment from OP:</p> <blockquote> <p>One further question with regards to not having to make a new instance of a Dog. If I am just taking out copies of the objects from the array list, how can I then take it out from the array list without having an object in which I put it? I just noticed as well that I didn't bracket the while-loop.</p> </blockquote> <p>A Java reference and the object it refers to are different things. They're very much like a C++ reference and object, though a Java reference can be re-pointed like a C++ pointer.</p> <p>The upshot is that <code>Dog dog;</code> or <code>Dog dog = null</code> gives you a reference that points to no object. <code>new Dog()</code> <em>creates</em> an object that can be pointed to.</p> <p>Following that with a <code>dog = al.get(i)</code> means that the reference now points to the dog reference returned by <code>al.get(i)</code>. Understand, in Java, objects are never returned, only references to objects (which are addresses of the object in memory). </p> <p>The pointer/reference/address of the Dog you newed up is now lost, as no code refers to it, as the referent was replaced with the referent you got from <code>al.get()</code>. Eventually the Java garbage collector will destroy that object; in C++ you'd have "leaked" the memory.</p> <p>The upshot is that you do need to create a variable that can refer to a Dog; you don't need to create a Dog with <code>new</code>. </p> <p>(In truth you don't need to create a reference, as what you really ought to be doing is returning what a Map returns from its get() function. If the Map isn't parametrized on Dog, like this: <code>Map&lt;Dog&gt;</code>, then you'll need to cast the return from get, but you won't need a reference: <code>return (Dog) map.get(id);</code> or if the Map is parameterized, <code>return map.get(id)</code>. And that one line is your whole function, and it'll be faster than iterating an array for most cases.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload