isEmpty issue while comparing java object - java

Currenty I have this NULL object for Employee Details to pass if employee details object created is empty
public static final EmployeeDetails NULL = new EmployeeDetails();
But I want to remove this now and use my regular EmployeeDetails object.
I was checking EmployeeDetails obj is empty or not by doing this if(!EmployeeDetails.NULL.equals(empDetails))
but now I dont have that object so I won't be able to do that way. I tried this way but got error saying isEmpty is not defined.
if(!empDetails.isEmpty())
Can someone tell me what I am suppose to do with this.
Thanks

isEmpty() is not defined because you did not define it. This funciton is not included in the handful of methods you get directly from Object and, in any case, an empty condition for your own objects should be defined by you since only you know the internal structure.
Of course, it all depends on what do you need because one person can take an isEmpty() method as valid by doing a simple null check while other person can make a field-by-field check.
In your case, just define an isEmpty method in your class. For example:
public boolean isEmpty() {
//your condition here, for example, I take an EmployeeDetails object
//as empty if it has no employee associated (assuming you can associate
//an employee to it).
return employee == null;
}
Remember to define WHEN do you consider this object to be empty and code the method with that in mind.

Add a method public boolean isEmpty() { // Implementation } ... here add your logic to find out the empty object, for example your previous code was checking the default value for all the properties to find out empty

Related

How can i access an element from a list in AssertJ?

assertThat(service.load(1, setup.getEntity(), "OBJECT1").getImages().get(0).isSwitchedOn()).isEqualTo(false);
I'm accesing the unique element of the list in this way,but i'm wondering if there's a more appropriate way to do it.
There is a method called singleElement() that can assert if a collection contain only one element.
There is also another method called extracting() which allow you to extract a property from an object for assertion.
Combing them will give you :
assertThat(list).singleElement().extracting(Image::isSwitchOn).isEqualTo(false);
Notice that extracting() will return you a generic object type for further chaining the assertion . If you want it to return a more specified boolean type , you can consider to use :
assertThat(list).singleElement().extracting(Image::isSwitchOn, as(BOOLEAN)).isFalse();
Or
assertThat(list).singleElement().extracting(Image::isSwitchOn).asInstanceOf(BOOLEAN).isFalse();
BOOLEAN is the static import from the class InstanceOfAssertFactories
I think , service.load(1, setup.getEntity(), "OBJECT1") returns list of images.
If you want to check the first element in the list of images for isSwitchedOn, the asset that statement is fine.
In case if you want to assert all the images -> isSwitchedOn, better use loop and use assertThat.
how about use public func? make it as a static func and put it in your tool-class.But if you just have one element,why not other structs?

Preventing duplicate items in list from printing to cell table gwt

If I have a class called 'TestClass' full of getters and setters, and then I set some properties on the class object in another class like so:
TestClass testClass = new TestClass();
testClass.setAppId("id");
testClass.setStatus("Status");
testClass.setMessage("Message");
List<TestClass> list = dataProvider.getList();
And then, before adding this object to my java list, I have to make sure it doesn't exist in the list to avoid duplicates.
To achieve this, I do the following check to see if all three properties of the corresponding values exist in the testClass object present in the list. If they don't, then it may be added to the list.
if(!list.contains(testClass.getAppId().equals("id")) &&
!list.contains(testClass.getStatus().equals("Status")) &&
!list.contains(testClass.getMessage().equals("Message"))) {
list.add(testClass);
}
dataProvider.refresh();
The above code is within a click handler, so is only ever executed when a button is clicked.
Why then, despite my futile attempt at stopping duplicates from entering the list, do I fail to stop duplicate records being added to my cell table in gwt?
Am I wrong in thinking the list logic is the problem?
Thank you for your help, I hope I've been thorough enough.
Your testClass.getAppId().equals("id") call returns true or false. Your list does not "contain" true or false therefore the condition becomes true and the element is added. The code should look like this:
for(TestClass testClass: list){
if(!testClass.getAppId().equals("id") &&
!testClass.getStatus().equals("Status") &&
!testClass.getMessage().equals("Message")){
list.add(testClass);
}
}
dataProvider.refresh();
testClass.getAppId().equals("id") returns true or false, weather your id equals to "id" or not. You then check if your list contains the return of this call. That's why you fail to maintain only unique items in your list.
You can create an equals/compare method in your testClass class so as to define in this function if the item that is going to be inserted already exists in your structure.
As a general approach is also better to use a hash in order to be sure that your data structure always stores unique items.

Is there a way to create an Immutable object in java, when the object have mutators?

This code is familiar.
List<Character> list = new ArrayList<Character>();
// populate the list
list.add('X');
list.add('Y');
// make the list unmodifiable
List<Character> immutablelist = Collections.unmodifiableList(list);
Now i have a typical Model Class with variables, getters and setters. Can i make that Object immutable,after i have invoked the setters i want? Something like this is my dream...
Person person = new Person();
person.setFirstName("firsName");
person.setLastname("lastName");
// i have a lot to set!!- Person is pretty large
// some way to do this
Person stubborn = Object.immutableObject(person);
I know there is no Object.immutableObject()..But is it possible to achieve something like this??
There's no general way to get this behavior.
You can create an ImmutablePerson class with a constructor that would accept a Person and construct an immutable version of that Person .
There is no way to do it without doing some work.
You need to either get a compile time check by creating a new immutable object from the mutable one as Eran suggests, add some code for a runtime check, or get a weaker compiler time check by using a split interface
e.g
interface ReadOnlyPerson {
int getX();
}
interface ModifiablePerson extends ReadOnlyPerson{
void setX();
}
class Person implements ModifiablePerson {
}
You can then pass out the immutable reference after construction.
However this pattern does not give a strong guarantee that the object will not be modified as the ReadOnlyPerson reference can be cast etc.
Sure, just have a boolean flag in the Person object which says if the object is locked for modifications. If it is locked just have all setters do nothing or have them throw exceptions.
When invoking immutableObject(person) just set the flag to true. Setting the flag will also lock/deny the ability to set/change the flag later.

Method "contains".Java List

I have Spring MVC appication. I have entity class Examination. I overridden method eqauls so I could use method contains of List interface. When i try to add new exam, I look if i have already added it. But when i pass examination object to mathod contains, I always have different students. For example:
I need to add exam to Student Jone. I try to add it and get another information: Kate : Jone, instead of Jone : Jone. I do not know why i happens because i pass examination object when i set student as Jone.
#Override
public boolean equals(Object arg) {
Examination exam = (Examination) arg;
System.out.println(exam.getStudent().getStudentFullName() + ":" + this.getStudent().getStudentFullName());
if (!this.subject.getSubjectTitle().equals(exam.getSubject().getSubjectTitle()))
return false;
else
return true;
}
piece of code where i try to add exam
examination.setStudent(currentStudent); // set student
examination.setSubject(subjectExam); // set subject
if(es.selectAllExams().contains(examination)) {
return "error";
} else {
es.insertExam(examination); // add to database
return "success";
}
In the equals method you are comparing only titles, not the student name. So if you have two examinations with same title, but different student name they are equal (based on your equals method). Compare also students in the equals method and you should be good. In general it is good practice to override both equals and hashcode methods.
Your implementation of equals method is in general not following best practices for overriding equals method. Google a bit for "java equals method best practices" - you'll find something like this : http://javarevisited.blogspot.sk/2011/02/how-to-write-equals-method-in-java.html
If you are lazy to write your own equals or hashcode methods (or you have other reasons) you can use :
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/builder/EqualsBuilder.html
or
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html
You say you override equals()
so I could use method contains of List interface
However, you don't have to override that method to use contains(). There's a default implementation that's suitable for most purposes; it boils down to "are these objects the same instance?". As a previous responder pointed out, you're breaking this logic with your implementation; all examinations with the same title will be considered the same object, so as long as your list has one examination with the same title as the one you're trying to add, the contains() check will always return true, and you'll never be able to add another one.
If you do want equality to be based on the title and student in question, then the previous answer is correct - you'll want to override both hashCode() and equals(), making sure you consider all fields important to an examination's identity in both methods.

Can I use only the key field to check equals? And can I use equals through subclasses?

I have a class Player with some fields:
String name;
Point position;
Action action;
The 'name' field is sort of a key, there cannot be 2 players with the same name. So it seems to me they are equals if the 'name' (probably case ignored) is the same. So do I use the String.equalsIgnoreCase(String) only or do I check the other fields as well?
1) Should I check more than the name field in the equals method of Player?
2) Should I throw an error in the equals method if the other fields are not the same?
3) And is it wise to check that one field only for subclasses, because even in subclasses the same name, indicates the same player, or should I choose another method for comparing this? Example:
class MovingPlayer extends Player{
Point destination;
So the 'name' field is still the key (something like an inter-subclass key).
Thanks in advance, Tjen
You should ask yourself the question -- is it possible for two objects with the same name property and two different position properties to exist in your application? If that is true, then you should implement the equals method to use all relevant fields.
You dont throw an error in the equals method. You return true or false.
Your subclasses can override the equals method. In that overridden method, you can check for superclas equals and only if they are equal, you continue with additional checking.

Categories

Resources