How can I use instanceof Keyword Java - java

Is this the right way of validating using the instanceof keyword in java? Can I not use the || operator with this keyword? I am seeing errors in the line where I am writing the if condition to check if FieldName < = 0 and also when I am checking if it is equal to null or empty. Can anyone help me with the right way of writing the following piece of code. Thank you.
public static boolean validation(Object FieldName, String Name) {
if(FieldName instanceof Integer) {
if ((int) FieldName < = 0) {
errorCode = "EXCEPTION";
errorMsg = "Required field " + Name + " was not provided";
logger.debug(Name+ " is null ");
return true;
}
else {
}
}
else if (FieldName instanceof String) {
if(FieldName == null || FieldName.equals("")) {
errorCode = "EXCEPTION";
errorMsg = "Required field " +Name+" was not provided";
logger.debug(Name+" is null ");
return true;
}
//Here I check the fields for null or empty
}

Why not have two methods, one which takes an Integer and validates that, and one that validates Strings? Would that be simpler?

The line needs to be changed to
if (((int) FieldName) <= 0) {
when you don't put the parentheses around the cast completely the compiler will still believe it is an object and not an integer.

Try this. change the if and else body according to you
public static boolean validation(Object FieldName, String Name) {
if (FieldName instanceof Integer) {
if (((Integer)FieldName) <= 0) {
//an integer <= 0
return true;
} else {
// an integer >= 0
return true;
}
} else if (FieldName instanceof String) {
if (FieldName == null || FieldName.equals("")) {
// a String empty or null
return true;
}
else {
// a String non empty
return true;
}
}
return false;
}

Related

Java equals method not behaving as expected

package restaurantclient;
public class Restaurant extends Store {
//Instance Variables
private int peopleServed;
private double averagePrice;
//Constructor with 3 parameters
public Restaurant(String storename, int peopleServed, double averagePrice) {
super(storename);
setPeopleServed(peopleServed);
setAveragePrice(averagePrice);
}
//Getters (Accessors)
public int getPeopleServed() {
return peopleServed;
}
public double getAveragePrice() {
return averagePrice;
}
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
//toString Method [Must Override]
#Override
public String toString() {
String information = "Store name: " + (super.getName());
information += "\n" + "The number of people served: " + peopleServed;
information += "\n" + "The average price per person: $" + averagePrice;
return information;
}
//Equals Method
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!(this.getName().equals(otherRestaurant.getName())))
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed))
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
return true;
}
public double getAverageTaxes() {
double total;
total = this.getPeopleServed() * this.getAveragePrice()
* super.CA_TAX_RATE;
return total;
}
}
package restaurantclient;
public class Store {
//Instance Variables
protected final double CA_TAX_RATE = 0.0884;
private String storename;
//Constructor
public Store(String storename) {
setName(storename);
}
//Getters (Accessors)
public String getName() {
return storename;
}
//Setters (Mutators)
public void setName(String storename) {
this.storename = storename;
}
//toString Method [Must Override]
#Override
public String toString() {
String directory = "Name of store: " + storename;
return directory;
}
//Equals Method
public boolean equals (Store storename) {
if (this == storename)
return true;
if (storename == null)
return false;
if (!(storename instanceof Store))
return false;
return true;
}
}
Above are the equals methods I'm calling. They are displaying the wrong answers: it should be in the first instance, "They are not equal" and in the second instance after setting everything equal to each other, it should display, "They are equal". I have tried very hard on this problem and many things have not worked. There are no overt errors it runs fine, but I am doing something wrong and some precise guidance would be a lot of help. Much of the vague hints have got me nowhere. I need something concrete, if this makes to you. Thanks again for the help. The following is the Client class:
package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonald's", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
System.out.println();
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal."); //SHOULD say "not equal" here EVERY TIME the second instance (next comment down) says "Equal"...this should never change.
System.out.println();
}
System.out.println();
r2.setName(r1.getName());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal."); //Now that everything is equal, it should print "The Objects are Equal" but it doesn't. It's in lock-step with the previous instance. Changing some things like return true to return false might make both these instances "Are equal" and some might change them to "Not Equal" but they are never the way I want them, which is when 2 changes are made, they are not equal (first case) and when the third and final change is made (like this case here on this line) it should say "the obj are equal" but it doesn't.
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by the restaurant is: $");
System.out.println(r1.getAverageTaxes());
}
}
The reason that I see is simple, you are not getting the same name.
In equals, you are comparing super.getName() with otherRestaurant.getName()
If the superclass of Restaurant have a different format or return an other variable, since you compare it to Restaurant.getName(), this will compare different value. Using this.getName() to compare the same variable (or format of variable) is safer. Even if Restaurant.getName() is only returning the super.getName(), this would be safer if you changed the method of Restaurant (because you prefer it an other way).
Here is an example :
Restaurant:
public String getName(){
return "A restaurant " + name;
}
Super class :
public String getName(){
return name;
}
Will result into comparing "A restaurant : KFC" with "KFV".
Using the same getter assure you to return the same "format".
Aslo, your logic is wrong. You want to check if one of the value is different, if it is, return false. And if you reach the end of the method, meaning there where no difference leading to a return false, you return true.
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!super.getName().equals(otherRestaurant.getName())) // added ! here
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed)) // change to != here
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
//No differences, then it is equals.
return true;
Note :
This condition could be shorten
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
Since it is doing the same thing (comparing the values) :
if (averagePrice != (otherRestaurant.averagePrice))
return false;
Edit :
You are having a problem of overriding.
In Store:
public boolean equals(Store s){}
And in Restaurant
public boolean equals(Object o){}
Since you are calling the method with a Restaurant (subclass of Store), the JVM will use the Store.equals method since it match the type, Restaurant.equals is not overriding it, it override the method in Object. Change to Store.equals(Object o) to correct this.
The method equals comes from Object so it should be always receiving an Object to prevent any problem like this one, if you specify the type in a method, it will not override correctly the method (depending on the type)
Seems you are checking for equality and then returning false, when you should check for not equality to return false.
else if (!super.getName().equals(otherRestaurant.getName()))
return false;
else if (peopleServed != (otherRestaurant.peopleServed))
return false;
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
Also as asked, any reason to uses super.getName() ?
And since peopleServed & averagePrice cannot be null, the -1 check is not needed as the expected result we be the same as the equality check
And finally, I'm guessing the end return should be true, as it means it's different instance of an object, but they have all the same attributs.
Within your equals() method , If super.name() equals otherRestaurant.name() shouldn't you return true, here:
else if (super.getName().equals(otherRestaurant.getName())) return false;
Ok, that one will work in any cases:
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (name == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (name!=otherRestaurant.getName())
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != otherRestaurant.peopleServed)
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != otherRestaurant.averagePrice)
return false;
return true;
}
check it and reply if it is ok

Alternative to boolean recursion

I can't seem to think of a way to solve this. At least not an elegant way. The function should determine if a given tree is a binary search tree. It seems to work (no duplicates are allowed now though).
This is where the function starts:
isBinarySearchTree(root)
Function:
public static boolean isBinarySearchTree(Node node) {
if (node.leftchild != null) {
if (node.leftchild.key < node.key)
isBinarySearchTree(node.leftchild);
else {
System.out.println("false: " + node + " -> " + node.leftchild);
return false;
}
}
if (node.rightchild != null) {
if (node.rightchild.key > node.key)
isBinarySearchTree(node.rightchild);
else {
System.out.println("false: " + node + " -> " + node.rightchild);
return false;
}
}
return true;
}
Obviously there is something wrong with the way I want to return. This would work if all the boolean return values would be in a logical && chain. The return value should only be true if all return values are true.
How would I have to rewrite the function to work like that? Or is it even possible?
This should work, I guess :
public static boolean isBinarySearchTree(Node node, int key) {
if (node.leftchild != null && node.leftchild.key < key || node.rightchild != null && node.rightchild.key > key) {
return false;
} else {
return (node.leftchild != null ? isBinarySearchTree(node.leftchild, node.leftchild.key) : true) && (node.rightchild != null ? isBinarySearchTree(node.rightchild, node.rightchild.key) : true);
}
}
You need to logically AND the results of your test on the left and test on the right, and return the result, something like return (leftnode == null || (leftnode.key < key && isBinarySearchTree(leftnode))) && (rightnode == null || (key < rightnode.key && isBinarySearchTree(rightnode)));. It might be clearer to break that into several lines, though.
public static boolean isBinarySearchTree(Node node) {
if(node==null)
return false;
if(node.left!=null &&node.key <node.left||node.right!=null &&node.key >node.right)
return false;
if((getMax(node.left)>getMin(node.right)) //Left subtree should not have a value which larger than min in right subtree
return false;
//check recurisvely left and right subtrees
if(!(isBinarySearchTree(node.left)&&isBinarySearchTree(node.right)))
return false;
return true;

Check if all values in a map are equal

I need to check if all values in a map are equal. I have a method to perform this task but would like to use a library or native methods. Limitations: Java 5 + Apache Commons libraries.
public static boolean isUnique(Map<Dboid,?> aMap){
boolean isUnique = true;
Object currValue = null;
int iteration = 0;
Iterator<?> it = aMap.entrySet().iterator();
while(it.hasNext() && isUnique){
iteration++;
Object value = it.next();
if(iteration > 1){
if (value != null && currValue == null ||
value == null && currValue != null ||
value != null && currValue != null & !value.equals(currValue)) {
isUnique = false;
}
}
currValue = value;
}
return isUnique;
}
What about this something like this:
Set<String> values = new HashSet<String>(aMap.values());
boolean isUnique = values.size() == 1;
how about
return (new HashSet(aMap.values()).size() == 1)
I know the original questions asks for solutions in Java 5, but in case someone else searching for an answer to this question is not limited to Java 5 here is a Java 8 approach.
return aMap.values().stream().distinct().limit(2).count() < 2
You could store the values in a Bidirectional Map and always have this property.
public static boolean isUnique(Map<Dboid,?> aMap) {
Set<Object> values = new HashSet<Object>();
for (Map.Entry<Dboid,?> entry : aMap.entrySet()) {
if (!values.isEmpty() && values.add(entry.getValue())) {
return false;
}
}
return true;
}
This solution has the advantage to offer a memory-saving short cut if there are many differences in the map. For the special case of an empty Map you might choose false as return value, change it appropriately for your purpose.
Or even better without a Set (if your Map does not contain null-values):
public static boolean isUnique(Map<Dboid,?> aMap) {
Object value = null;
for (Object entry : aMap.values()) {
if (value == null) {
value = entry;
} else if (!value.equals(entry)) {
return false;
}
}
return true;
}
As my comment above:
//think in a more proper name isAllValuesAreUnique for example
public static boolean isUnique(Map<Dboid,?> aMap){
if(aMap == null)
return true; // or throw IlegalArgumentException()
Collection<?> c = aMap.getValues();
return new HashSet<>(c).size() <= 1;
}

How to avoid many if-else with many condition

I need some help with designing the logic of my problem.
Model Bean
package com.ashish.model;
public class Model {
public Integer a,b,c,d;
public String f,g,h,i,j;
}
Service Class
package com.ashish.service;
import com.ashish.model.Model;
public class Service {
public StringBuilder query = null;
public Service(){
query = new StringBuilder("Select * from A where ");
}
public String build(Model m){
if(m.a != null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);
if(m.a == null&&m.b!=null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("b="+m.b);
if(m.a == null&&m.b==null&&m.c!=null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("c="+m.c);
if(m.a == null&&m.b==null&&m.c==null&&m.d!=null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("d="+m.d);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e!=null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("e="+m.e);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f!=null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("f="+m.f);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g!=null&&m.h==null&&m.i==null&&m.j==null)
query.append("g="+m.g);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h!=null&&m.i==null&&m.j==null)
query.append("h="+m.h);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i!=null&&m.j==null)
query.append("i="+m.i);
if(m.a == null&&m.b==null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j!=null)
query.append("j="+m.j);
if(m.a != null&&m.b!=null&&m.c==null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" b="+m.b);
if(m.a != null&&m.b==null&&m.c!=null&&m.d==null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" c="+m.c);
if(m.a != null&&m.b==null&&m.c==null&&m.d!=null&m.e==null&&m.f==null&&m.g==null&&m.h==null&&m.i==null&&m.j==null)
query.append("a="+m.a);query.append(" d="+m.d);
// ... 512 lines in this pattern
return query.toString();
return query.toString();
}
}
I want to write public String build(Model m) in such a way so that I would not have to write 512 if-else condition.
Conditions:
All instance variables of Model class can have two value ( null, not null)
They all can be null or they all can be not null.
There would be total 512 combinations ( since every instance variable have two state and there are 9 instance variable so total number of condition would be 2^9 )
Order of the instance variable does not matter.
My project use Java 6 so I can not use switch on String.
I have looked into various pattern but none of them is meeting my requirement.
Thanks for looking
A private helper method as follows should do it -
private void appendIfNotNull(String fieldOp, String val) {
if(val != null) {
query.append(fieldOp).append(val);
}
}
Then just call it in the build method -
public String build(Model m) {
appendIfNotNull("a=", m.a); //no null check, just need to repeat this for all fields
Maybe you want to try to use Java Reflection to read all fields of your Model and read them. You don't need to know the field name to read it. So it would be fully dynamic and generic, even if you extend your Model class.
Class modelClass = Class.forName(Model.class.getName());
Field[] fields = circleClass.getFields(); //includes all fields declared in you model class
for (Field f : fields) {
System.out.println("field " + f.getName() + " has value: " + f.get(<YOUR_MODEL_INSTANCE>));
}
Example code adapted from:
- http://forgetfulprogrammer.wordpress.com/2011/06/13/java-reflection-class-getfields-and-class-getdeclaredfields/
Will this code make sense?
interface ToStringer {
void appendTo(StringBuilder sb);
}
class NullToStringer implements ToStringer {
public void appendTo(StringBuilder sb) {
// Do nothing
}
}
class IntegerToStringer implements ToStringer {
private String fieldName;
private Integer val;
public IntegerToStringer(String fieldName, Integer val) {
this.fieldName = fieldName;
this.val = val;
}
public void appendTo(StringBuilder sb) {
sb.append(field).append(" = ").append(val);
}
}
public class ToStringFactory {
public ToStringer getToStringer(String fieldName, Integer val) {
if (val == null) {
return new NullToStringer();
} else {
return new IntegerToStringer(fieldName, val);
}
}
public ToStringer getToStringer(String fieldName, String val) {
...
}
}
public String build(Model m){
ArrayList<ToStringInstance> list = ...;
list.add(ToStringFactory.getToStringer("f", m.f));
list.add(ToStringFactory.getToStringer("g", m.g));
list.add(ToStringFactory.getToStringer("h", m.h));
StringBuilder sb = ...;
for (ToStringInstance tsi : list) {
tsi.appendTo(sb);
}
return sb.toString();
}
I am not sure what logic you are trying to implement, but the general approach: creating interface, concrete implementaion of printing values, using NullValue pattern to hide null problem and using factory to control objects creation should do the trick.
By using this approach you can avoid problems with 2^9 combinations by avoiding multiple if-else statements.
Update. Just came to my mind. You can use reflection. Iterate through all fields, get value of each, print it if it is no null. Maybe this will be enough.
It seems like you want to append to the query for each element that is not null. This can be done quite simply with an auxiliary method or two:
public class Service {
public StringBuilder query = null;
public Service(){
query = new StringBuilder("Select * from A where ");
}
public String build(Model m) {
boolean added = first;
first &= !maybeAdd("a", m.a, first);
first &= !maybeAdd("b", m.b, first);
. . . // all the rest of the fields of m
}
/**
* Add an equality test to an SQL query if the value is not {#code null}.
* #param key the field name for the query
* #param value the value to test for equality
* #param first flag indicating that no conditions have been added
* #return {#code true} if the value was appended; {#code false} otherwise.
*/
private boolean maybeAdd(String key, Object value, boolean first) {
if (value != null) {
if (!first) {
query.append(" AND ");
}
query.append(key).append('=').append(value);
return true;
}
return false;
}
}
Note that if all fields of the model are null, your query will not be correctly formed. You might want to include the appropriate logic in the maybeAdd method to compensate for that.
As I mentioned in my comment, you don't need a different if for every combination. You just need to append the values that are not null, and ignore the ones that are. Let me know if this works for you.
public String build(Model m) {
// use this to know when to add " AND " to separate existing values
boolean appended = false;
if (m.a != null) {
query.append("a=" + m.a);
appended = true;
}
if (m.b != null) {
if (appended) {
query.append(" AND ");
}
query.append("b=" + m.b);
appended = true;
}
if (m.c != null) {
if (appended) {
query.append(" AND ");
}
query.append("c=" + m.c);
appended = true;
}
if (m.d != null) {
if (appended) {
query.append(" AND ");
}
query.append("d=" + m.d);
appended = true;
}
if (m.e != null) {
if (appended) {
query.append(" AND ");
}
query.append("e=" + m.e);
appended = true;
}
if (m.f != null) {
if (appended) {
query.append(" AND ");
}
query.append("f=" + m.f);
appended = true;
}
if (m.g != null) {
if (appended) {
query.append(" AND ");
}
query.append("g=" + m.g);
appended = true;
}
if (m.h != null) {
if (appended) {
query.append(" AND ");
}
query.append("h=" + m.h);
appended = true;
}
if (m.i != null) {
if (appended) {
query.append(" AND ");
}
query.append("i=" + m.i);
appended = true;
}
if (m.j != null) {
if (appended) {
query.append(" AND ");
}
query.append("j=" + m.j);
appended = true;
}
return query.toString();
}
I don't know why you need two if statements for this:
if( m.a == null) {
query.append("m=null");
} else {
query.append("m="+m.a);
}
if( m.b == null) {
query.append("m=null");
} else {
query.append("m="+m.b);
}

Checking JSP Input for "Empty"

In my testing, the following seems to cover everything I can think of in terms of ensuring that a field is populated. Can anyone think of a case I might have missed?
public static boolean isEmpty(final String string) {
return string != null && !string.isEmpty() && !string.trim().isEmpty();
}
The name is a bit misleading as the method is labeled "isEmpty" but will return true when it's not empty... but that's up to you.
I would change your AND statements to ORs and remove the middle term as it is superfluous e.g.
public static boolean isEmpty(final String string) {
return string == null || string.trim().isEmpty();
}
EXAMPLE:
if(isEmpty(null)){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty(" ")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("Test")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
OUTPUT:
Empty
Empty
Empty
Not Empty
Why don't you just use a library?
One example is Apache's Common Utils:
StringUtils.isBlank()
StringUtils.isNotBlank()
Apache Commons StringUtils uses the following techniques:
isEmpty:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
isBlank:
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
You can just do:
public static boolean isEmpty(String string) { //don't make it final going in or you cant trim it.
string = string.trim();
return string != null || string.length() == 0;
}

Categories

Resources