New user held with searching array - java

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

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
}

Java Replace / Improve null check

I have a pseudo Java method where everything can be nullable:
private String prepareMessage(Scope scope) {
if (scope != null) {
if (scope.getPermission != null) {
if (scope.getInfo != null) {
return "Successful";
} else {
return "Missing field Info";
}
} else if (scope.getInfo() != null) {
return "Permission field not provided";
}
}
return "Permission and Info fields not provided";
}
How can I simplify this code to remove terrible looking null checks? Thanks !
You can create a helper method that suits you, an example:
public String notNullOrElse(Object o, String notNull, String isNull) {
return null != o ? notNull : isNull;
}
Then you can change:
if (scope.getInfo != null) {
return "Successful";
} else {
return "Missing field Info";
}
to:
return notNullOrElse(scope.getInfo(), "Successfull", "Missing field Info");
However, sometimes those horrible null checks are unfortunately necessary.
Tried refactoring the code. In most cases you can simplify If - else by re ordering the code flow. This makes getting code coverage easy.
private String prepareMessage(Scope scope) {
if (scope == null) {
return "Permission and Info fields not provided";
}
if (scope.getPermission != null && scope.getInfo != null) {
return "Successful";
} else {
return scope.getPermission == null ? "Permission field not provided" : "Missing field Info";
}
}
This doc beautifully explains code smells in if-else ->
https://dzone.com/articles/code-smells-if-statements
Java 1.7 introduces the class java.util.Objects (this link is from the Java 11 JavaDoc, but that should not matter here).
That class provides the methods Objects.isNull() and Objects.nonNull() that can be used as follows in your code:
import static java.util.Objects.*;
…
private String prepareMessage(Scope scope) {
if (nonNull (scope)) {
if (nonNull (scope.getPermission())) {
if (nonNull (scope.getInfo())) {
return "Successful";
} else {
return "Missing field Info";
}
} else if (nonNull (scope.getInfo()) {
return "Permission field not provided";
}
}
return "Permission and Info fields not provided";
}
Whether this looks better or not is a matter of taste, of course.
Alternative logic may look like this (for Java 11):
import static java.util.Objects.*;
…
private String prepareMessage( Scope scope )
{
var messages = { "Successful", "Missing field Info", "Permission field not provided", "Permission and Info field not provided" };
var index = 0;
var retValue = messages [3]; // No scope at all
if( nonNull( scope ) )
{
if( isNull( scope.getPermission() ) ) index += 2;
if( isNull( scope.getInfo() ) ) index += 1;
retValue = messages [index];
}
return retValue;
}
I do not want to say that this is really better in any way, it is just different. And it spares one null check …

Java: Set.contains() gives wrong result

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

How do I use contains to search through a custom object ArrayList for a particular string?

I'm completely brand new to programming (started yesterday...) and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos and I want to be able to search through the inventory to check if a particular video is there.
I know I can use contains to do this but I can't get it to work with my custom objects ArrayList (videos) and I want it to search through all the data (each InventoryRow below). I've overridden equals and HashCode but it still won't work - whenever I try to run the code it will always tell me it can't find the video even if the video is there. (FYI I use contains towards the end of my code under the rent and check functions)
I'd really appreciate any help as I've been googling all day to no avail. Also if this can't be done or another method would be better please let me know! Thanks.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class InventoryRow {
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availability == null) ? 0 : availability.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((returndate == null) ? 0 : returndate.hashCode());
result = prime * result + ((type == null) ? 0 : type.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;
InventoryRow other = (InventoryRow) obj;
if (availability == null) {
if (other.availability != null)
return false;
} else if (!availability.equals(other.availability))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (returndate == null) {
if (other.returndate != null)
return false;
} else if (!returndate.equals(other.returndate))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability,
String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"1 January 2015"));
videos.add(new InventoryRow("2012", "Regular", 'Y', "1 January 2015"));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', "1 January 2015"));
// Another ArrayList because I can't seem to search through the first
// one?
/*ArrayList<String> names = new ArrayList<String>();
names.add("Casablanca");
names.add("Jurassic Park");
names.add("2012");
names.add("Ant-Man");*/
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("What do you want to do?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// Search through ArrayList
if (videos.contains(line2)) {
System.out.println("Video available to rent!");
} else {
System.out.println("Video unavailable to rent.");
}
// Check function
} else if (line.equals("c")) {
System.out
.println("Which video would you like to check is in the inventory?");
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(line3)) {
System.out.println("Video found!");
} else {
System.out
.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// If anything else is entered
} else {
System.out
.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
You can use contains. But, for the first day of programming, it might be more understandable to simply iterate over your inventory, comparing the input string with the video name:
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
Alternative to #kilo answer, you could implement equals and hashcode method only on the name of video class and check it in the following way.
String line3 = input.nextLine();
// Search through ArrayList
if (videos.contains(new Video(line3, null, null, null))) {
System.out.println("Video found!");
}
This will return contains = true only if the name matches.

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

Categories