Java: Set.contains() gives wrong result - java

Since Set.contains(Object o) should just use equals to check if an object is in a Set, how can the following two methods produce different results? In my project, method 1 does not throw an exception, but method 2 does throw an exception.
For information, the object "group" is in the set "groups", so Method 1 works like I would expect it.
boolean java.util.Set.contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Method 1:
boolean ex = true;
for (AccessControlGroup acg : groups) {
if ((acg.equals(group))) {
ex = false;
}
}
if (ex) {
throw new IllegalStateException("Invalid group");
}
Method 2:
if (!(groups.contains(group))) {
throw new IllegalStateException("Invalid group");
}
Further information:
HashSet is used.
AccessControlGroup:
public List<AccessControlGroup> getInherits() {
if (this.inherits == null) {
this.inherits = new ArrayList<>();
}
return this.inherits;
}
public void setInherits(List<AccessControlGroup> inherits) {
this.inherits = inherits;
}
public List<AccessControlPermission> getPermissions() {
if (this.permissions == null) {
this.permissions = new ArrayList<>();
}
return this.permissions;
}
public void setPermissions(List<AccessControlPermission> permissions) {
this.permissions = permissions;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
// prevent infinity loops or other sick effects
// result = prime * result + ((this.inherits == null) ? 0 : this.inherits.hashCode());
result = prime * result + ((this.permissions == null) ? 0 : this.permissions.hashCode());
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControlGroup other = (AccessControlGroup) obj;
// prevent infinity loops or other sick effects...
// if (!Objects.equal(this.inherits, other.inherits)) {
// return false;
// }
if (!Objects.equals(this.permissions, other.permissions)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
AccessControl:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControl other = (AccessControl) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}

I'll lay odds that you modified group after adding it to the set groups. That would change its hashCode, which would leave it in the wrong bucket in groups, which would mean contains would not find it anymore unless the new hashCode happened to collide with the old one.
Set< AccessControlGroups > groups = new HashSet<>();
AccessControlGroup group = new AccessControlGroup();
groups.add( group );
groups.contains( group ); // true
group.setPermissions( new ArrayList<>() );
groups.contains( group ); // false

Related

How to create a Junit test for the below code

I am able to get the coverage for the second and the third condition but not able to get the coverage for the last and the first one.
#Override public boolean equals(Object obj)
{
if(this == obj) {
return true;
}
if(obj == null)
{
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
Rating other = (Rating) obj;
boolean bool= score == other.score ;
boolean bool2=Objects.equals(user, other.user);
return bool&&bool2;
}
the below one is my test function
public void equalsTest_lastcondition() {
Rating test=new Rating();
Object obj2=testwa2;
Rating other = (Rating) obj2;
boolean bool=false;
if(other.getScore()==testwa1.getScore())
{ bool=true;}
boolean bool2 =Objects.equals(test.getUser(), other.getUser());
assertEquals(true, bool && bool2);
}
this == obj is simple test.equals(test)
getClass() != obj.getClass() is test.equals("").
PS: You can use any object instead of String there.
#Test
void equalsTest() {
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
assertTrue(rating.equals(rating)); // 1. if statement
assertFalse(rating.equals(null)); // 2. if statement
assertFalse(rating.equals(score)); // 3. if statement
assertTrue(rating.equals(new Rating(score, user))); // other statements
}
Updated:
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
#Test
void equalsShouldReturnTrueWhenComparingTheSameInstance() {
assertTrue(rating.equals(rating)); // 1. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheNullValue() {
assertFalse(rating.equals(null)); // 2. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheWrongType() {
assertFalse(rating.equals(score)); // 3. if statement
}
#Test
void equalsShouldReturnTrueWhenComparingNewInstanceWithSameValues() {
assertTrue(rating.equals(new Rating(score, user))); // other statements
}

StackOverflowError in equals method of bidirectional objects

I have to objects Client and Order and these objects are living in bidirectional relation and I try to write them to file, but I get StackOverflowError. I got this error because my equals methods are looped.
My classes which I try to serialize:
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Client implements Serializable {
private Long id;
private String name;
private List<Order> orders = new ArrayList<>();
public void addOrder(Order order) {
order.setClient(this);
orders.add(order);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Client client = (Client) o;
if (id != null ? !id.equals(client.id) : client.id != null) return false;
if (name != null ? !name.equals(client.name) : client.name != null) return false;
return orders != null ? orders.equals(client.orders) : client.orders == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (orders != null ? orders.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Client{" +
"id=" + id +
", name='" + name + '\'' +
// ", orders=" + orders.size() +
'}';
}
}
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Order implements Serializable {
private Long id;
private String name;
private Client client;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
if (id != null ? !id.equals(order.id) : order.id != null) return false;
if (name != null ? !name.equals(order.name) : order.name != null) return false;
return client != null ? client.equals(order.client) : order.client == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (client != null ? client.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Order{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
#Data
#AllArgsConstructor
public class MapDataSource implements Serializable {
private final Map<Date, List<Client>> clients = new HashMap<>();
private final Map<Date, List<Order>> orders = new HashMap<>();
}
#Slf4j
public class ObjectWriter {
private final String fileName = "data.obj";
public void write(String fileName, MapDataSource mapDataSource) {
try (
FileOutputStream fs = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fs)
) {
oos.writeObject(mapDataSource);
log.info("Object has been written.");
} catch (IOException ioe) {}
}
}
#Slf4j
public class ObjectReader {
private static final String fileName = "data.obj";
public MapDataSource readObj(String fileName) {
MapDataSource mapDataSource = null;
try (
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis)
) {
mapDataSource = ((MapDataSource) ois.readObject());
// log.info("Read object: {}", mapDataSource);
} catch (IOException ioe) {
} catch (ClassNotFoundException classEx) {
System.out.println();
}
return mapDataSource;
}
}
And when I try to run code below I get StackOVerflowError:
String testFile = "testFile.obj";
final DateTime time = new DateTime(2017, 12, 1, 10, 0);
final Client client1 = new Client(1L, "Client1", new ArrayList<>());
final Order order1 = new Order(1L, "Order1", null);
final MapDataSource mapDataSource = new MapDataSource();
mapDataSource.getClients().put(time.toDate(), new ArrayList<>());
mapDataSource.getClients().get(time.toDate()).add(client1);
mapDataSource.getOrders().put(time.toDate(), new ArrayList<>());
mapDataSource.getOrders().get(time.toDate()).add(order1);
new ObjectWriter().write(testFile, mapDataSource);
final MapDataSource found = new ObjectReader().readObj(testFile);
System.out.println(found);
Solution:
MapDataSource needs to have implemented equals() and hashcode() methods.
It seems like you need to sit down and seriously consider what it should even mean for two clients or orders to be equal in the first place. The Long id; makes me wonder whether you should really be comparing the object graphs in the first place. If e.g. clients have unique IDs, then it could make sense to just ensure that clients are unique object instances and then you do away with the problem entirely.
If you really do need to compare object graphs, you could use something like the following. We use an IdentityHashMap to record all of the objects we've seen, then if we detect a cycle, we just compare the previously-stored counter values which tells us if the two graphs have the same cycle.
Client and Order need to share code (so the maps can be passed around), so you just override equals in both to return ClientOrderEquality.equals(this, that).
import java.util.*;
public final class ClientOrderEquality {
private ClientOrderEquality() {}
private static final class Counter { long value; }
public static boolean equals(Client lhs, Client rhs) {
return equals(lhs, new IdentityHashMap<>(),
rhs, new IdentityHashMap<>(),
new Counter());
}
public static boolean equals(Order lhs, Order rhs) {
return equals(lhs, new IdentityHashMap<>(),
rhs, new IdentityHashMap<>(),
new Counter());
}
private static boolean equals(Client lhs,
Map<Object, Long> seenL,
Client rhs,
Map<Object, Long> seenR,
Counter counter) {
if (lhs == null || rhs == null)
return lhs == rhs;
Long countL = seenL.putIfAbsent(lhs, counter.value);
Long countR = seenR.putIfAbsent(rhs, counter.value);
if (countL != null || countR != null)
return Objects.equals(countL, countR);
counter.value++;
if (lhs == rhs)
return true;
if (!Objects.equals(lhs.id, rhs.id))
return false;
if (!Objects.equals(lhs.name, rhs.name))
return false;
if (lhs.orders.size() != rhs.orders.size())
return false;
Iterator<Order> itL = lhs.orders.iterator();
Iterator<Order> itR = rhs.orders.iterator();
while (itL.hasNext() && itR.hasNext())
if (!equals(itL.next(), seenL, itR.next(), seenR, counter))
return false;
return true;
}
private static boolean equals(Order lhs,
Map<Object, Long> seenL,
Order rhs,
Map<Object, Long> seenR,
Counter counter) {
if (lhs == null || rhs == null)
return lhs == rhs;
Long countL = seenL.putIfAbsent(lhs, counter.value);
Long countR = seenR.putIfAbsent(rhs, counter.value);
if (countL != null || countR != null)
return Objects.equals(countL, countR);
counter.value++;
if (lhs == rhs)
return true;
if (!Objects.equals(lhs.id, rhs.id))
return false;
if (!Objects.equals(lhs.name, rhs.name))
return false;
return equals(lhs.client, seenL, rhs.client, seenR, counter);
}
}
I assume if you want to actually use that code, you'll need to alter it to use whatever getter naming format you're using and write a hashCode implementation. You'll also need to consider subtypes correctly if you're extending Client and Order.

Testing controllers using Spring, JUNIT, MockMvc and Hamcrest

I am trying to test a controller of mine which returns me a List of Objects on the get method to populate a dropdown on my page.
I am trying to write a JUnit test using MockMvc and Hamcrest to test the same.
I want to compare the List of objects and test if it fails or not.
I have created a static List of objects in my Test.java and I am getting a List of objects from the model.attribute method.
To Test: if both the List of Objects are equal and don't contain any other objects.
My object is called Option which has 3 properties. Key, Value and Selected. I have to check if the all the keys exists in the List or not.
I am unable to create a matcher to do the same. I am trying to create a matcher to compare my List.
So far I have done the following:
#Before
public void setup() throws Exception {
// This would build a MockMvc with only the following controller
this.mockMvc = MockMvcBuilders.standaloneSetup(openAccountController)
.build();
}
#Test
public void testOpenAccount() {
try {
setAllLegislations();
this.mockMvc
.perform(get("/open_account.htm"))
// This method is used to print out the actual httprequest
// and httpresponse on the console.
.andDo(print())
// Checking if status is 200
.andExpect(status().isOk())
.andExpect(
model().attributeExists("appFormAccountPlans",
"appFormLiraLegislations",
"appFormLrspLegislations",
"appFormRlspLegislations"))
.andExpect(
model().attribute("appFormAccountPlans", hasSize(5)))
.andExpect(
model().attribute("appFormLiraLegislations",
hasSize(8)))
.andExpect(
model().attribute("appFormLrspLegislations",
hasSize(2)))
.andExpect(
model().attribute("appFormRlspLegislations",
hasSize(1)))
.andExpect(
model().attribute(
"appFormLiraLegislations",
hasKeyFeatureMatcher(getLiraLegislations(allLegislations))));
private Matcher<List<Option>> hasKeyFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "was") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (actualOptions.size() == expectedOptions.size()) {
for (Option expectedOption : expectedOptions) {
for (Option actualOption : actualOptions) {
if (expectedOption.getKey().equals(
actualOption.getKey())) {
flag = true;
} else {
flag = false;
break;
}
}
}
}
if (flag)
return actualOptions;
else
return null;
}
};
}
private List<Option> getLiraLegislations(List<Option> legislation) {
List<Option> liraLegislations = new ArrayList<Option>();
Iterator<Option> iterator = legislation.iterator();
while (iterator.hasNext()) {
Option option = iterator.next();
if (LIRA_LEGISLATIONS.contains(option.getKey())) {
liraLegislations.add(option);
}
}
return liraLegislations;
}
private List<Option> allLegislations;
public List<Option> getAllLegislations() {
return allLegislations;
}
public void setAllLegislations() {
allLegislations = new ArrayList<Option>();
for (String key : ALL_LEGISLATIONS) {
Option option = new Option();
option.setKey(key);
allLegislations.add(option);
}
}
private static final Set<String> ALL_LEGISLATIONS = new HashSet<String>(
Arrays.asList(AccountLegislationEnum.AB.toString(),
AccountLegislationEnum.MB.toString(),
AccountLegislationEnum.NB.toString(),
AccountLegislationEnum.NL.toString(),
AccountLegislationEnum.NS.toString(),
AccountLegislationEnum.ON.toString(),
AccountLegislationEnum.QC.toString(),
AccountLegislationEnum.SK.toString(),
AccountLegislationEnum.BC.toString(),
AccountLegislationEnum.FE.toString(),
AccountLegislationEnum.NT.toString(),
AccountLegislationEnum.PE.toString(),
AccountLegislationEnum.YT.toString(),
AccountLegislationEnum.NU.toString(),
AccountLegislationEnum.UNKNOWN.toString()));
This is how I am getting my model attribute as:
Attribute = appFormLiraLegislations
value = [com.abc.arch.core.gui.eform.gui.Option#199d1739, com.abc.arch.core.gui.eform.gui.Option#185fac52, com.abc.arch.core.gui.eform.gui.Option#312a47fe, com.abc.arch.core.gui.eform.gui.Option#4edc8de9, com.abc.arch.core.gui.eform.gui.Option#71e8e471, com.abc.arch.core.gui.eform.gui.Option#70edf123, com.abc.arch.core.gui.eform.gui.Option#15726ac1, com.abc.arch.core.gui.eform.gui.Option#abeafe7]
Thanks in advance.
You can make your life definitely easier when you correctly implement Option object hashCode() and equals() methods using key attribute; then you can simply write:
model().attribute("appFormLiraLegislations",getLiraLegislations(allLegislations)))
and rely on list1.equals(list2) method to do the work for you.
Option hashCode and equals implementation:
public class Option {
private String key;
private String label;
...
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Option other = (Option) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
Methods above are generated by my IDE. I also don't know exactly what is structure of your Option class, so I add label property for example in addition to key property.
I created a custom Hamcrest matcher to compare the List of Option by checking the size and the keys.
private Matcher<List<Option>> hasOptionsFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "Options were") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (expectedOptions.size() == actualOptions.size()) {
for (Option expected : expectedOptions) {
for (Option actual : actualOptions) {
if (expected.getKey().equals(actual.getKey())) {
flag = true;
break;
} else {
flag = false;
}
}
}
} else
flag = false;
if (flag)
return expectedOptions;
else
return null;
}
};
Implementation would be as follows:
private static final ImmutableBiMap<String, String> LIRA = new ImmutableBiMap.Builder<String, String>()
.put(AccountLegislationEnum.AB.toString(), "ALBERTA")
.put(AccountLegislationEnum.MB.toString(), "MANITTOBA")
.put(AccountLegislationEnum.NB.toString(), "NEW BRUNSWICK")
.put(AccountLegislationEnum.NL.toString(), "NEWFOUNDLAND")
.put(AccountLegislationEnum.NS.toString(), "NOVA SCOTIA")
.put(AccountLegislationEnum.ON.toString(), "ONTARIO")
.put(AccountLegislationEnum.QC.toString(), "QUEBEC")
.put(AccountLegislationEnum.SK.toString(), "SASKATCHEWAN")
.put(AccountLegislationEnum.UNKNOWN.toString(), "UNKNOWN").build();
private List<Option> prepareOptions(ImmutableBiMap<String, String> map) {
List<Option> legislations = new ArrayList<Option>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Option option = new Option();
option.setKey(key);
option.setValue(value);
legislations.add(option);
}
return legislations;
}
.andExpect(model().attribute("appFormLiraLegislations",hasOptionsFeatureMatcher(prepareOptions(LIRA))))

Compare two list objects in java

I have the following simple java program to compare two objects in list.
public static void main( String[] args )
{
UserInfo user=new UserInfo();
user.setDomainId(2);
user.setId("sxpadmin");
user.setStatus("active");
UserInfo user1=new UserInfo();
user1.setDomainId(2);
user1.setId("sxpadmin");
user1.setStatus("active");
System.out.println(user.equals(user1));
List<UserInfo> userinfo=new ArrayList<UserInfo>();
userinfo.add(user);
userinfo.add(user1);
HashSet<UserInfo> set = new HashSet<UserInfo>();
for (UserInfo temp : userinfo)
{
if(set.contains(temp)){
System.out.println("same");
}
else{
System.out.println("different");
set.add(temp);
}
}
}
Now I am comparing the two objects and it should take to if block as the content in both the objects is same.
I am iterating the userinfo object and comapring its elements and also I am adding it to set hoping to avoid the duplicates.But none of them worked. Help me in solving this.
Hashcode and equals methods in UserInfo are
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + customer_id;
result = prime * result
+ ((domainId == null) ? 0 : domainId.hashCode());
result = prime * result
+ ((last_name == null) ? 0 : last_name.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((first_name == null) ? 0 : first_name.hashCode());
// Added by Sandip on 04 Jan 2013 for 2 FA
result = prime * result
+ ((seed_value == null) ? 0 : seed_value.hashCode());
// End added by Sandip on 04 Jan 2013 for 2 FA
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserInfo other = (UserInfo) obj;
if (customer_id != other.customer_id)
return false;
if (last_name == null) {
if (other.last_name != null)
return false;
} else if (!last_name.equals(other.last_name))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (first_name == null) {
if (other.first_name != null)
return false;
} else if (!first_name.equals(other.first_name))
return false;
// Added by Sandip on 04 Jan 2013 for 2 FA
if (seed_value == null) {
if (other.seed_value != null)
return false;
} else if (!seed_value.equals(other.seed_value))
return false;
// End added by Sandip on 04 Jan 2013 for 2 FA
if (domainId == null) {
if (other.domainId != null)
return false;
} else if (!domainId.equals(other.domainId))
return false;
return true;
}
If you want to create working solution here's what you have to override equals and hashCode method.
Many IDE's have feature to autogenerate those methods for chosen class. Following code of UserInfo shows methods generated by IntelliJ:
public class UserInfo {
private int domainId;
private String id;
private String status;
public void setDomainId(int domainId) {
this.domainId = domainId;
}
public void setId(String id) {
this.id = id;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
if (domainId != userInfo.domainId) return false;
if (id != null ? !id.equals(userInfo.id) : userInfo.id != null) return false;
if (status != null ? !status.equals(userInfo.status) : userInfo.status != null) return false;
return true;
}
#Override
public int hashCode() {
int result = domainId;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
return result;
}
}
It's important to remember that if certain class doesn't implement those methods then hashCode is returning hash of objects address in memory and equals is using this default version of hashCode.
Code pasted above is working with code pasted by you. My output is:
true
different
same

New user held with searching array

I am trying to search an array and if the two Strings are matched then it will return true otherwise false, firstly i want to search to see if the account is already there if so then search Code if the two exsis then return true
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)) {
for (Accounts c : bAccounts) {
if (c.getCode().equals(Code))
return true;
}
}
}
return false;
}
Think I've got a little lost within this search method, can anyone please help me on this, thanks. This all compiles fine but doesn't seem to return anything. I have get methods in my Accounts class which has get and set methods for Account and Sort.
public boolean searchArray(String account, String code) {
for (Accounts a : bAccounts) {
if (a.getAccount().equals(account)
&& a.getCode().equals(code)) {
return true;
}
}
return false;
}
Inner for should be removed.
You didn't mention if you'll accept nulls for account and code parameters.
If null values are possible/desirable to compare, this is what I suggest:
public boolean searchArray(String account, String code) {
for (Account a : accounts) {
if (account == null) {
if (code == null) {
if ((a.getAccount() == null) && (a.getCode() == null)) {
return true;
}
} else {
if ((a.getAccount() == null) && code.equals(a.getCode())) {
return true;
}
}
} else {
if (code == null) {
if (account.equals(a.getAccount()) && (a.getCode() == null)) {
return true;
}
} else {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
}
}
return false;
}
If you won't consider nulls for account and code parameters, I suggest this:
public boolean searchArray(String account, String code) {
// if you won't consider nulls then there's no need to search
// when at least one of them is null
if ((account == null) || (code == null)) {
return false;
}
for (Account a : accounts) {
if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
return true;
}
}
return false;
}
Hope it helps you

Categories