I have been looking around for some answers to this question and I just can't seem to figure it out. I think that the issue seems to be with the 'scope' of my code but I don't know what I'm doing wrong and I could really use some help. I'm very new to Java.
My goal
Test to see if an object already exists in an array before adding it.
If the object already exists in the array, return null.
If it doesn't exist in the array, create it and then return it.
The Code
public Business addBusiness(String person, String business, String location) {
int id = 0;
for (Business business : businesses ) {
if (business.getPerson().equals(person)) {
if (business.getBusiness().equals(business)) {
if (business.getLocation().equals(location)) {
return null;
}
}
}
}
Business newBusiness = new Business(person, business, location, id);
return newBusiness;
}
What happens when I run it
When I run the code it will just happily create object after object with the same details. This leads me to believe that there is a problem with my logic. I was expecting that when it returned null, that would be the end of it.
I would appreciate any tips you can give me on solving this problem.
EDIT: The 'Business' class
public class Business {
// Attributes //
private String person, business, location;
private int id;
// Constructor //
public Business(String person, String business, String location, int id) {
this.person = person;
this.business = business;
this.location = location;
this.id = id;
}
// Getters //
public String getPerson() {
return person;
}
public String getBusiness() {
return business;
}
public String getLocation() {
return location;
}
public int getId() {
return id;
}
}
Try
public Business addBusiness(String person, String business, String location)
{
int id = 0;
for (Business b : businesses ) {
if (b.getPerson().equals(person)) {
if (b.getBusiness().equals(business)) {
if (b.getLocation().equals(location)) {
return null;
}
}
}
}
Business newBusiness = new Business(person, business, location, id);
return newBusiness;
}
You were masking the parameter business from the function's signature with the object you're iterating over in the loop. Renaming this to b avoids the issue.
Okay -- so I think that I figured it out. Thank you so much to everyone for your help on this matter.
public Business addBusiness(String person, String business, String location)
{
int id = 0;
for (Business business : businesses ) {
if (business.getPerson().equals(person)) {
if (business.getBusiness().equals(business)) {
if (business.getLocation().equals(location)) {
return null;
}
}
}
}
Business newBusiness = new Business(person, business, location, id);
return newBusiness;
}
The issue was caused because I never actually added my newBusiness object into the array once it was created. So every time it ran it would never match an existing entry because there were no entries in the array.
The correct code should be something like:
public Business addBusiness(String person, String business, String location)
{
int id = 0;
for (Business b : businesses ) {
if (b.getPerson().equals(person)) {
if (b.getBusiness().equals(business)) {
if (b.getLocation().equals(location)) {
return null;
}
}
}
}
Business newBusiness = new Business(person, business, location, id);
b.add(newBusiness); // This was the missing line, now it seems to work fine.
return newBusiness;
}
Clearly, I still have a lot to learn.
Related
Suppose that there are classes like:
CivilAddSystem class :
class CivilAddSystem{
List<People> people = new ArrayList<>();
List<Town> towns = new ArrayList<>();
public People addPeople(People people) {
people.add(people);
return people;
}
public Town addTown(Town town) {
towns.add(town);
return town;
}
public House addHouse (House house, String townName) throws IllegalStateException {
Town town = getTown(townName);
if (null == town) throw new IllegalStateException("No matching town");
town.addHouse(house);
return house;
}
public List<String> getTown(String name) {
for (Town town : towns) {
if (town.getName().equals(name)) return town;
}
return null;
}
}
Town class:
public class Town {
List<House> houses = new ArrayList<>();
String name;
String abbreviation;
public Town (String name, String abbreviation) {
this.name = name;
this.abbreviation = abbreviation;
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public void addHouse(House house) {
houses.add(house);
}
public House getHouse(String unitNumber) {
for (House house : houses) {
if (house.getUnitNumber().equals(unitNumber)) return house;
}
return null;
}
}
House class:
public class House {
private final List<People> people = new ArrayList<>();
private final String unitNumber;
private final String houseName;
public House (String unitNumber, String houseName) {
this.unitNumber= unitNumber;
this.houseName= houseName;
}
public String getUnitNumber() {
return unitNumber;
}
public String getHouseName() {
return houseName;
}
private People checkMovedInPeople(People person) {
if (null == person) throw new NullPointerException();
for (People movedIn : people) {
if (movedIn.getName().equals(person.getName())) return movedIn;
if (movedIn.getPersonID().equals(person.getPersonID())) return movedIn;
}
return null;
}
public void moveInPeople(People person) throws IllegalArgumentException, IllegalStateException {
if (null == person) throw new IllegalArgumentException("Person shouldn't be null");
if (null != checkMovedInPeople(person)) throw new IllegalStateException("Person is already in the house");
people.add(person);
}
public List<String> getPeople() {
List<String> results = new ArrayList<>();
for (People person: people) {
results.add(person.getPersonID());
}
return results;
}
public People getPerson(String match) {
for (People person: people) {
if (person.getPersonID().equals(match)) return person;
if (person.getName().equals(match)) return person;
}
return null;
}
}
And for the people class, it just has two variables: String PersonID and String Name and their getter methods.
So, what I want to achieve is that, I am currently trying to test the addPeople method in CivilAddSystem class and I want to test it independently using mockito.
The test case I wrote using JUnit is like this:
#Test
public void testAddPeople() {
CivilAddSystem CAS = new CivilAddSystem();
Town town = CAS.addTown("BlueTown", "BT");
House house = CAS.addHouse("U180", "BlueHouse", "BlueTown");
People bob = CAS.addPeople("1", "Bob");
Assert.assertEquals(CAS.getTown("BlueTown").getHouse("U180").getPerson("1"), null);
house.moveInPeople(bob);
Assert.assertEquals(CAS.getTown("BlueTown").getHouse("U180").getPerson("1").getPersonID, 1);
}
But I am really struggling with applying mockito for this test case.
What I did so far is just mocking Town, House and People classes, (not the CivilAddSystem class since it is the one that is being tested), and stopped there...
Can anyone gives me a hint on how to apply mockito for that above test case?
p.s) A little bit of modification for the codes above is accepted (for example, applying dependency injection and something like this are accepted).
Thanks in advance!
Mocking gives you the ability to have a class look like another class or a class matching an interface. So if you wanted to test Town, you don't want to go through creating Houses, you just use Mockito to mock the house.
Ideally, Dwelling would be an interface, and there would be House, TownHome, Condo, RanchHouse, etc. as implementations. Then, when you are testing the CivilAddSystem, you aren't testing any of the TownHome implementation code. You have isolated it so that you are just testing the one class.
So you could create something like this:
// unit tests should only test one piece of functionality at a time.
// This should only test the addition of a Person. You should expect
// to have lots of unit tests so that when one breaks, you can tell
// exactly what broke
#Test
public void testAddTown() {
Town mockedTown = Mockito.mock(Town.class);
CivilAddSystem CAS = new CivilAddSystem();
Town town = CAS.addTown(mockedTown);
// verify that the town that was put in is the same as you get out...
// note that you should not be testing the functionality of Town here
// if you do, this breaks the isolation
Assert.assertTrue(CAS.getTowns().contains(mockedTown));
}
For advanced functionality, you can stub functionality. For example, if you needed to test if it was a large city, and CAS
// checks this by determining if the population is > 100000
#Test
public void testAddTown() {
Town mockedTown = Mockito.mock(Town.class);
when(mockedTown.getPopulation()).thenReturn(100001)
CivilAddSystem CAS = new CivilAddSystem();
// verify that the current state is the expected state
Assert.assertEquals(CAS.getNumberOfLargeTowns(), 0);
// make a change
Town town = CAS.addTown(mockedTown);
// test that the updates state is as expected
Assert.assertEquals(CAS.getNumberOfLargeTowns(), 1);
}
I am new to collections and looking for help. I am trying to search a map using a key, and return the values of the key which is from another object. This is my code so far.
public class Employer {
Map<String, NewHire> employee = new HashMap<>();
}
public void addEmployee(String fullName, String age, String location, String JobTitle) {
NewHire newEmployee = new NewHire(age, location, JobTitle);
this.employee.put(fullName, newEmployee);
}
The code for the other object is -
public class NewHire {
private String age;
private String location;
private String jobTitle;
}
public NewHire(String aAge, String aLocation, String aJobTitle) {
this.age = aAge;
this.location = aLocation;
this.jobTitle = aJobTitle;
}
I then create like so -
Employer CompanyA = new Employer();
CompanyA.addEmployee("JohnSmith", "23", "London", "Service Desk");
I wanted to create a method that can search the map for a key specified by the user, in this case "JohnSmith", and if found, it then shows me the age, location and jobTitle of that person but I really am not sure how I would go about this.
The best way to go about it in my opinion is the way Titulum said, using Optional.
I would just leave another way, a bit not so nice, but you may understand it better.
You can Override the toString() method in the NewHire class and use it, or create getters for the properties:
#Override
public String toString(){
return String.format("Age: %s\nLocation: %s\nJobTitle: %s", age, location, jobTitle);
}
// getters
public String getJobTitle() {
return jobTitle;
}
public String getLocation() {
return location;
}
public String getAge() {
return age;
}
On your Employer class, if you want to use the not so much nicer way of doing it (although i recommend using Optional):
public NewHire getEmployeeByName(String fullName){
return employee.get(fullName);
}
Then to use it:
Employer employer = new Employer();
employer.addEmployee("JohnSmith", "23", "London", "Service Desk");
NewHire newHire = employer.getEmployeeByName("sJohnSmith");
if(newHire != null) {
System.out.println(newHire.toString());
// using getters
System.out.println(newHire.getAge());
System.out.println(newHire.getJobTitle());
System.out.println(newHire.getLocation());
}
You can simply write the method as follows:
public Optional<NewHire> findByFullName(String fullName) {
return Optional.ofNullable(employee.get(fullName));
}
This will return you an Optional, which is an Object in Java that contains either something or nothing. To see if the Optional contains anything you can do:
Optional<NewHire> possiblyFoundNewHire = findByFullName("SomeName");
possibleFoundNewHire.ifPresent(newHire -> {
System.out.println(newHire); // Or formatted as you would like.
});
I have an class IntegrationWithDB in which i have to method getConnection()and selectFromDB().
In the selectFromDb() i have a result set , i want to get the result
set vales in another class method
Actually it did but it only shows the last value of dataBase table.
Note i have made getter and setter method in IntegrationWithDB class and use in selectFromDB() method.
public void selectFromDB() {
try {
if (this.conn == null) {
this.getConnection();
}
if (this.stmt == null) {
this.stmt = this.conn.createStatement();
}
int success = 0;
this.query = "select * from contacts order by node_id";
this.rs = this.stmt.executeQuery(query);
// something is wrong in the while loop
while (rs.next()) {
setId(rs.getInt("node_id")); // i made getter and setter for id, name, parent and for level
setNam(rs.getString("node_name"));
setParnt(rs.getString("node_parent"));
setLvl(rs.getInt("node_parent"));
}
if (success == 0) {
this.conn.rollback();
} else {
this.conn.commit();
}
} catch (Exception ex) {
ex.printStackTrace();
}
and in another class test i have method displayList() in this method i write the following code
public class test {
IntegrationWithDbClass qaz = new IntegrationWithDbClass();
public void displayList ( ) {
qaz.getConnection();
qaz.selectFromDB();
for(int i = 0; i< 5; i++){
System.out.println(" "+qaz.getId());
System.out.println(" "+qaz.getNam());
}
}
when i initilize the displayList() method in the main method , it shows the following result
5
red
how can i get all the five values?
First of all you have to create what is commonly referred to as an Entity class. This is the class that represents a single row in your database. This should ideally be separate from the code that interacts with the database connection.
So first step, create a class named Contact, and in it put the 4 fields you have, id, name, parent and level, with the respective getter methods. If you do not expect these to change by your program make them immutable, it is the good practice to ensure consistency. So something like:
public class Contact {
private final int id;
private final String name;
private final String parent;
private final String level;
public Contact(String id, String name, String parent, String level) {
this.id = id;
this.name = name;
this.parent = parent;
this.level = level;
}
public int getId() {
return id;
}
//... put the rest of the getter methods
}
Then in your IntegrationWithDB class (I would rename this to something more meaningful like ContactRepository) you can change that method you have to:
public List<Contact> getContacts() {
// ... your database connection and query code here
this.rs = this.stmt.executeQuery(query);
List<Contact> contacts = new LinkedList<Contact>();
while (rs.next()) {
int id = rs.getInt("node_id");
String name = rs.getString("node_name");
String parent = rs.getString("node_parent");
String level = setLvl(rs.getInt("level"));
contacts.add(new Contact(id, name, parent, level));
}
//... the rest of your database handling code, don't forget to close the connection
return contacts;
}
Then from displayList() you just have to call getContacts() which gives you a list of Contact objects to iterate through.
I assume that currently you're storing those properties in int/string variables. In every iteration of the loop you're overwriting the values. What you need to do is to store them in some collection like ArrayList and in each iteration add() to this collection.
I have used One-to-Many Mapping in my project. I have stored a list of clicks for every user.
But when I retrieve the list by calling getClicks() methodm Hibernate returns list in different format.
Something like this.
"[com.zednx.tech.persistence.Click#29df9a77]"
So I tried Reading Every value from the list and assign to a new List.
List<Click> clicks=new ArrayList<Click>();
for(Click c: e.getClicks()){
Click temp = new Click();
temp.setAff_source(c.getAff_source());
temp.setCb_to_award(c.getCb_to_award());
temp.setCb_type(c.getCb_type());
clicks.add(temp);
}
But when i print the items of new List it stills prints the same way.
I need to build a JSON from the resulting String of this list.
So if the list is returned in format, it wont help me.
I couldn't find anything regarding this except How to pretty print Hibernate query results?
I tried Arrays.ToString(Object o). But it doesn't work.
GSON builder part-
Gson gson = new GsonBuilder()
.registerTypeAdapter(Click.class, new MyTypeAdapter<Click>())
.create();
List<Click> clicks=new ArrayList<Click>();
for(Click c: e.getClicks()){
Click temp = new Click();
temp.setAff_source(c.getAff_source());
temp.setCb_to_award(c.getCb_to_award());
temp.setCb_type(c.getCb_type());
temp.setCom_to_recieve(c.getCom_to_recieve());
temp.setStore_name(c.getStore_name());
temp.setT_date(c.getT_date());
temp.setT_status(c.getT_status());
temp.setT_ticket(c.getT_ticket());
temp.setUid(c.getUid());
System.out.println(c.toString());
clicks.add(temp);
}
String json = gson.toJson(clicks, Click.class);
Click.java
#Entity
#Table(name="click")
public class Click {
#Id
#Column(name="t_ticket")
private String t_ticket;
#Column(name="uid",nullable=false)
private long uid;
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
#ManyToOne
#JoinColumn(name="uid",
insertable=false, updatable=false,
nullable=false)
private Earning earning;
#Column(name="store_name")
private String store_name;
#Column(name="t_status")
private String t_status;
#Column(name="aff_source")
private String aff_source;
#Column(name="com_to_recieve")
private float com_to_recieve;
#Column(name="t_date")
private Date t_date;
#Column(name="cb_to_award")
private float cb_to_award;
#Column(name="cb_type")
private String cb_type;
public String getT_ticket() {
return t_ticket;
}
public void setT_ticket(String t_ticket) {
this.t_ticket = t_ticket;
}
public Earning getEarning() {
return earning;
}
public void setEarning(Earning earning) {
this.earning = earning;
}
public String getStore_name() {
return store_name;
}
public void setStore_name(String store_name) {
this.store_name = store_name;
}
public String getT_status() {
return t_status;
}
public void setT_status(String t_status) {
this.t_status = t_status;
}
public String getAff_source() {
return aff_source;
}
public void setAff_source(String aff_source) {
this.aff_source = aff_source;
}
public float getCom_to_recieve() {
return com_to_recieve;
}
public void setCom_to_recieve(float com_to_recieve) {
this.com_to_recieve = com_to_recieve;
}
public Date getT_date() {
return t_date;
}
public void setT_date(Date t_date) {
this.t_date = t_date;
}
public float getCb_to_award() {
return cb_to_award;
}
public void setCb_to_award(float cb_to_award) {
this.cb_to_award = cb_to_award;
}
public String getCb_type() {
return cb_type;
}
public void setCb_type(String cb_type) {
this.cb_type = cb_type;
}
Any Help is appreciated.
You need to implement a toString method, as your current Click class likely doesn't have one, so it just prints as the name of the class and instance identifier.
Okay, I could solve my problem finally.
I made another POJO without any annotations and Mapped the List items to that POJO class.
I think the problem was with Annotation of mapping on another class which I had in original POJO.
Also getString() method only helps in changing format of identifier. So basically it has nothing to do with JSON building unless you format getString() in form of JSON.
Hope it helps. If anyone wants new temp POJO I made I can post it if requested.
Thanks.
If I want to validate my input, should I make validation code as private helper methods or create a separate static helper class? Does the validation code increase the size of the object?
More Information
Let's say I have a class
import java.util.Vector;
public class Place {
private final double longitude;
private final double latitude;
private final String id;
private String address;
private String name;
private String types;
private String icon;
private String phoneNumber;
private String websiteUrl;
private int rating;
private Vector<Integer> challenges;
public static class Builder {
// required parameter
private final double longitude;
private final double latitude;
private final String id;
// optional parameter
private String address = "n/a";
private String name = "n/a";
private String icon = "n/a";
private String phoneNumber = "n/a";
private String websiteUrl = "n/a";
private String types = "n/a";
private Vector<Integer> challenges = new Vector<Integer>();
private int rating = 0;
public Builder(double longitude, double latitude, String id) {
assert(longitude >= -180.0 && longitude <= 180.0);
assert(latitude >= -90.0 && longitude <= 90.0);
this.longitude = longitude;
this.latitude = latitude;
this.id = id;
}
public Builder address(String address) {
this.address = address;
return this;
}
public Builder types(String types) {
this.types = types;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder icon(String icon) {
this.icon = icon;
return this;
}
public Builder phoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public Builder websiteUrl(String websiteUrl) {
this.websiteUrl = websiteUrl;
return this;
}
public Builder builder(int rating) {
this.rating = rating;
return this;
}
public Place build() {
return new Place(this);
}
}
public Place(Builder builder) {
// required parameters
longitude = builder.longitude;
latitude = builder.latitude;
id = builder.id;
// optional parameters
address = builder.address;
types = builder.types;
name = builder.name;
icon = builder.icon;
phoneNumber = builder.phoneNumber;
websiteUrl = builder.websiteUrl;
rating = builder.rating;
challenges = builder.challenges;
}
public double getLongitude() {
return longitude;
}
public double getLatitude() {
return latitude;
}
public String getId() {
return id;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setIconUrl(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setWebsiteUrl(String websiteUrl) {
this.websiteUrl = websiteUrl;
}
public String getWebsiteUrl() {
return websiteUrl;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getRating() {
return rating;
}
#Override
public String toString() {
return "(" + Double.toString(longitude) + ", " + Double.toString(latitude) + ")";
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : 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;
Place other = (Place) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
public Vector<Integer> getChallenges() {
return new Vector<Integer>(challenges);
}
public void addChallenges(Integer i) {
this.challenges.add(i);
}
public void showChallenges() {
for (Integer i : challenges) {
System.out.print(i + ", ");
}
}
}
If I have to validate address argument before setting it, where should I put the code for validating address in this case?
If you are talking just seeing if the entered String is formatted correctly or if the length is right, then you would use a private method. If you would on the other hand check if the address is correct (look it up on a map) or any more advanced stuff, it would make sense to create a AddressValidator interface and call it from that private method.
The reason for the private method being that you call this both from a constructor, setter or any other method that could suppy an address. The reason for the interface being that you might want to have e.g. an online / offline AddressValidator (MockAddressValidator, or one that calls a different class for each country etc).
As an AddressValidator could be reused in other classes, and to keep your code clean, I would create it as a top level interface + OnlineAddressValidator. This makes your class better readable as well. For full configurability, you might want to think about how you are going to supply the AddressValidator instance, e.g. through the constructor or one defined as a static final validator.
public interface AddressValidator {
static class AddressValidatorResult {
// some results, you might want to return some useful feedback (if not valid)
boolean isValid() {
throw new IllegalStateException("Method not implemented yet");
}
}
public static class AddressValidationException extends Exception {
private AddressValidationException(AddressValidatorResult result) {
// add some implementation
}
}
// don't throw ValidateException here, invalid addresses are normal for
// validators, even if they aren't for the application that uses them
AddressValidatorResult validateAddress(String address);
// don't throw ValidateException here, invalid addresses are normal for
// validators, even if they aren't for the application that uses them
}
public class DefaultAddressValidator implements AddressValidator {
public static class Params {
// some parameters for this specific validator
}
private final Params params;
public DefaultAddressValidator(Params params) {
// creates this validator
this.params = params;
}
#Override
public AddressValidatorResult validateAddress(String address) {
// perform your code here
// I don't like "return null" as it may lead to bugs
throw new IllegalStateException("Method not implemented yet");
}
}
// and use it like this
private void validateAddress(String address) throws AddressValidationException {
// e.g. field AddressValidator set in constructor
AddressValidatorResult result = addressValidator.validateAddress(address);
if (!result.isValid()) {
throw new AddressValidationException(result);
}
}
Should I make validation code as private helper methods or create a separate static helper class?
This totally depends on your context. It's impossible to say what should be the best design, without knowing what you are trying to realise.
After you edit: IMO, it is still not easy to tell you. If you only have to validate the address in one single point of your application (id: the setter method), I would validate it inside the setter method. If the input was invalid, I whould throw an IllegalArgumentException.
Does the validation code increase the size of the object?
However, the answer to your second question is No. To understand why, you have to know what Object Oriented Programming is.
Some references:
http://en.wikipedia.org/wiki/Object-oriented_programming
http://en.wikipedia.org/wiki/Class_(computer_science)
Should I make validation code as private helper methods or create a
separate static helper class?
It depends if you think that you'll need to reuse the same method also in another class for the same purpose(input validation) it is better write the method in a separate static helper class so you can reuse the method and maintain it easily.
If you write the same private helper method in several class each time that you need to make a changes you have to edit each method in each class, with a static helper class you change the code in one place only ...
Read about PropertyChangeListener and Bean Validation.
I tend to validate within the get() and set() methods wherever possible - calling external static methods for common tasks such as checking dates or cleaning input (i.e. to avoid sql injection)
If you only use (and are only ever going to use) the validation within one class, keep it as a private helper method. If in doubt, I tend to pull the functionality out into a static helper class. It makes very little difference to the amount of code, is no more effort to implement, and is much more flexible.
The short answer is: you should implement your validation code the way that your framework tells you to. Typically, this is a public method or an annotation. An interface could work too. If you add code, your class size will increase.
Data validation should be automatically called by your software's infrastructure. This helps to prevent programmers from forgetting to call the appropriate code. So, the methods should be public (an interface would work too).
Frameworks like Struts, Spring, Hibernate and have their own validation systems. Java EE leverages bean validation.
I recommend bean validation, because it performs validation regardless of the input source. When most people think of input validation, they think of data coming from the user e.g. HTTP Request, command console, Swing text field. Spring and Struts validation is often fine for those situations. But in long lived programs developed for enterprises, other data feeds often get introduced e.g. SQL database updates from another programs, database restoration after a crash, enterprise service bus, JMS.
That is why I prefer bean validation. The downside is that "safe sources" (data that you know is untainted) are validated unnecessarily. But with today's processing power, that should rarely be a significant concern.
Java EE Tutorial