Iterator hasNext() Method - java

Why do we implement hasNext method as
public boolean hasNext() {
if(current != null)
return true;
return false;
}
instead of
public boolean hasNext() {
if(current.getNext() != null)
return true;
return false;
}

I don't know who we is but consider the following.
public boolean hasNext() {
if(current != null)
return true;
return false;
}
In the previous case, next() would return the value and update current.
public boolean hasNext() {
if(current.getNext() != null)
return true;
return false;
}
In this case, if getNext() is null, you still need to return the current value (e.g. current.getValue()) so you would miss the last one.
But keep in mind that hasNext() and next() don't work in isolation of each other. So it depends on how both are implemented as to whether either method makes sense.

Related

How should I define the contains() command for a LinkedList?

I currently am redefining the commands for a Linked list via recursion, where the public method takes in an object and calls the private contains() method which has a Node parameter but cannot seem to figure out the logic.
#Override
public boolean contains(Object o) {
if (o.equals(contains(o))) {
return true;
}
contains(o);
return false;
}
private boolean contains(Node node) {
if (node.next == null) {
return false;
}
if (node == node.next) {
return true;
}
return contains(node.next);
}
Assuming you are constrained to use recursion (not iteration), let's look at what you would need here:
Private recursive method
Recursive method must have a base case and a recursive call for a subproblem (in this case the rest of the list).
a) Base Case: In the base case here, you would either find the node with the expected key, or reach the end of the list, something like:
if (node == null) {
return false;
}
if (key.equals(node.key)) {
return true;
}
b) Recursive Call: You must call the method with the next node (rest of the list).
return contains(key, node.next);
Putting both the things together, you would get the following method:
private boolean contains(Object key, Node node) {
if (node == null) {
return false;
}
if (key.equals(node.key)) {
return true;
}
return contains(key, node.next);
}
Public method
The public method just takes a key and invokes the recursive method with node pointed to the head of the list.
#Override
public boolean contains(Object o) {
returns contains(o, this.head);
}
It would be helpful if you practice a few simple problems on recursion following the above template, just to get a hang of things.

Add exception to a boolean method

I have an equals method to compare some attributes, this is how it looks:
public boolean Complementos(COSTOS obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
COSTOS other = (COSTOS) obj;
if (NumeroParte == null) {
if (other.NumeroParte != null)
return false;
} else if (!NumeroParte.equals(other.NumeroParte))
return false;
if (descripcion == null) {
if (other.descripcion != null)
return false;
} else if (!descripcion.equals(other.descripcion))
return false;
if (Double.doubleToLongBits(monto) != Double.doubleToLongBits(other.monto))
return false;
if (referencia != other.referencia)
return false;
return true;
}
But besides to see if the attributes are equals, i want to return a value from "compareToIgnoreCase" from the attributes "-1, 0, 1" and i'm not allow to do it because of the method that is boolean and i tried to make it "int" but that would just mark as error my "return false/true", so... could i use an exception? if i could... how could i implemented?
Thanks
You could use an exception to convey this, but you definitely shouldn't. Exceptions are for exceptional circumstances and shouldn't be used to control the flow of your application.
Generally speaking, if you have a method that needs to return more than one output then you should split it into multiple methods. This makes your code more reusable and your APIs less confusing.
In the rare case where you can't do this, you can return an object representing the result of the method. For example:
#Transactional
public LoginResponse login(String username, char[] password);

Binary search tree String search

I have a program where I need to search for a specific word in a binary tree, the code I came up with for the search method for the string is not working. if someone could take a look at it I would greatly appreciate it.
I have tried a few alterations to this but it still did not work.
public boolean check(BSTNode t,String key){
if(!t.word.equals(key)){
check(t.left,key);
check(t.right,key);
}
else{
return true;
}
return false;
}
This could be written like this;
public boolean check(BSTNode t,String key) {
return
t.word.equals(key) || check(t.left,key) || check(t.right,key)
}
or, more verbosely;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
You don't need a lot of else statements because the return statements stop execution in the function.
Edit:
You must also check to see that your BSTNode is not null, or you will get null pointer exceptions when you reach the end of the tree. This could be done at the start of the function, or before the inner recursive check calls:
public boolean check(BSTNode t,String key) {
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
or;
public boolean check(BSTNode t,String key) {
if (t.word.equals(key)) return true;
if (t.left != null && check(t.left,key)) return true;
if (t.right != null && check(t.right,key)) return true;
return false;
}

Class equals method is confusing

I'm studying object oriented programming in Java at my school and I had to do an exercise to compare Circles.
I had the Circle Class with these
private int id;
private String bgColor;
private String fgColor;
And inside it I had to use the equals method to compare two circles (by using these three attributes): a circle is equal to other circle if its radius and the bg and fgColor are the same.
public boolean equals(Object obj) {
boolean found;
if (obj == null) {
found = false;
}
if (getClass() != obj.getClass()) {
found = false;
}
final Circle other = (Circle) obj;
if (Double.doubleToLongBits(this.radius) == Double.doubleToLongBits(other.radius)) {
//found = false;
if (Objects.equals(this.bgColor, other.bgColor)) {
//found = false;
if (Objects.equals(this.fgColor, other.fgColor)) {
return true;
}//end if fgColor
else{
found = false;
}
}//end if bgcolor
else{
found = false;
}
}//end if radius
else{
found = false;
}
return found;
}
But my teacher told me that the code above is "confusing", but I don't understand why.
Do you know a better solution?
My teacher wants that we folow this structure (this case is only comparing one property):
public boolean equals (Object obj)
{
boolean b;
if(obj == null)
{
b = false;
}
else
{
if(this == obj)//same object
{
b = true;
}
else
{
if(obj instanceof Book)
{
Book other = (Book) obj;
b = (this.id == other.id);
}
else
{
b = false;
}
}
}
return b;
}
This is about the most concise version (assuming that radius and colors can't be null). The null check for obj is taken care of by the instanceof test:
public boolean equals(Object obj) {
if( ! (obj instanceof Circle ) )
return false;
Circle rhs = (Circle)obj;
return Double.compare( radius, rhs.radius ) == 0 &&
bgColor.equals( rhs.bgColor ) &&
fgColor.equals( rhs.fgColor );
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
// its a Circle so its safe to case
Circle other = (Circle)obj;
// equals ONLY if 3 conditions are met
if (radius == other.getRadius() &&
bgColor.equals(other.getBgColor()) &&
fgColor.equals(other.getFgColor())){
return true;
}
return false;
}
If you are using a IDE (I hope you do) probably it has an option to generate code for equals method.
Eclipse generates something like:
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Circle other = (Circle) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (fgColor == null) {
if (other.fgColor != null)
return false;
} else if (!fgColor.equals(other.fgColor))
return false;
if (Double.doubleToLongBits(radius) != Double.doubleToLongBits(other.radius))
return false;
return true;
}
And don't forget implements hashcode method when you implements equals method and vicecersa.
Rather than having a single return statement consider using multiple return points to simplify the code. This way you do not need extra boolean variables to hold on to the results of prior conditions.
public class Circle {
public double radius;
public String bgColor;
public String fgColor;
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj instanceof Circle) {
Circle other = (Circle) obj;
if (Double.compare(this.radius, other.redius) == 0
&& compareStrings(this.fgColor, other.fgColor)
&& compareStrings(this.bgColor, other.bgColor)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
private boolean compareStrings(String a, String b) {
if (a == null && b == null) {
return true;
} else if (a != null) {
return a.equals(b);
} else if (b != null) {
return b.equals(a);
}
return false;
}
}
This solution allows for the possibility that either of the String fgColor or bgColor might be null without throwing a NPE. The String comparison has been extracted into its own function to aid readability and reduce confusion.
As a follow-up to my previous answer:
Writing an equals method that works correctly in the presence of subclassing is extremely non-trivial (see Joshua Bloch's comments in Item 8 of `Effective Java').
Indeed, until relatively recently the was no widely known single method for doing this.
In 2009, the article "How to Write an Equality Method in Java"
by Martin Odersky, Lex Spoon, and Bill Venners shows that this can be achieved in terms of a `canEqual' method.

Why Hashtable's equals method test the situation that value is null or not

I am reading the Hashtable's code, and I learned that both Hashtable's key and value can not be null, but its equals method test the situation that value is null or not.
public synchronized boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> t = (Map<K,V>) o;
if (t.size() != size())
return false;
try {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) { // Can Hashtable's value be null?
if (!(t.get(key)==null && t.containsKey(key)))
return false;
} else {
if (!value.equals(t.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
It is kind of a pattern that is followed throughout to handle the NPE. Consider a simple class
public class HelloWorld {
String data;
}
If you generate hashCode() and equals() you will see this general pattern followed. As in this case
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HelloWorld that = (HelloWorld) o;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
return true;
}
#Override
public int hashCode() {
return data != null ? data.hashCode() : 0;
}
As you can see we always check for null. It is not mandatory but a good programming practice. I understand it makes no sense in the case of Hashtable's but as I mentioned earlier developers must have added this check to maintain a uniform pattern.
Update : As Tim has suggested Since Hashtable is subclassable, it is possible for a subclass to try to support null keys or values. So it is safe to do a null check.

Categories