Noob Java question here. I am wondering if there is a standard way to add additional/external properties to a POJO. i.e., say I have a User Object that I add to an ArrayList in my program. This Object will contain things like first name, last name, address, email, phone, etc., corresponding to whatever is defined in my database.
Now say that I have the requirement to include external attributes along with said User, such as Employer ID, Vehicle Plate #, Smartphone type. I will need to be able to include these extra properties when adding a User to my ArrayList - Is it possible to attach these strictly with Java so that I can have acces to them?
I've thought of going with something like a Value Object, in where the VO would include all the User Properties along with the extra fields to be added from outside Classes, but want to explore more possibilities. Any ideas? Thanks much
You have many possibilities. Here are a few that immediately spring to mind:
Refactor the User class. This is the obvious one, so I presume you have a good reason for not doing so.
Write a class that extends User, containing this information. Presuming you're only storing this information for a subset of the users that this information applies to, this makes the most sense.
Use composition - create a new class that holds a user instance and then any other information you want to add to it.
One big influence on what design you use will be whether all additional values are unique, or if a User can have multiple smartphones, vehicles, etc.
If all additional fields are all unique you can just slide in java.util.Properties (or other Maps). Your User class needs at least
import java.util.Properties;
class User
{
Properties extra_attr = new Properties();
// ... existing code ...
public void setExtraAttr(String field, String value) {
extra_attr.setProperty(field,value);
}
public String getExtraAttr(String field) {
return extra_attr.getProperty(field);
}
}
Then use calls like some_user.setExtraAttr("Employer ID","314159"); and some_user.getExtraAttr("Employer ID"); to set and get your extra attributes.
If you need multiplicity you may need a different approach, or you can just code over your implementation of Properties. For instance, you can rewrite setExtraAttr() to look for existing keys and add an index
public void setExtraAttr(String field, String value) {
if(extra_attr.getProperty(field) == null)
extra_attr.setProperty(field,value);
else {
int index = 1;
while(extra_attr.getProperty(field+index) != null)
index++;
extra_attr.setProperty(field+index,value);
}
}
You then need some kind of loop where ever you get attributes to look for and handle the multiple extra records.
Related
I have an object the represent an entity. By example i have the "user" java object that have the followings field, String name, String first name, String address, boolean deadOrAlive. But now instead of having field i want to put them into a hashmap, so my first reflex was to make it this way :
private HashMap<String, Object> fieldsHM;
This would means that i have to cast my HM value when i want to use it and i don't want to make that because i need to know the type before i use my value. I want to make something like :
Set<String> keys = fieldsHM.keySet();
for(String key : keys) {
if(fieldsHM.get(key).isBoolean()) {
// Do the appropriate things
} else {
// Do the thing for this case...
}
}
I think it's possible in java, would this be good to do it this way ?
EDIT 1: I don't want to make a hashMap because this is not what i need. What i need is a way to browse the fields of the Entity user fields by fields, and depending the type of the field do the appropriate things.
I don't want to make a hashMap because this is not what i need. What i
need is a way to browse the fields of the Entity user fields by
fields, and depending the type of the field do the appropriate things.
I guess that would be a job for Reflection, like User.class.getFields().
It will still be uncomfortable to distinguish between primitive field, but you could use their wrapper classes instead.
But whatever path you choose, I think there would be a better solution if you would state what the actual goal is.
Depending on your actual use case, it might make sense to use JSON (maybe with databind) or even a database.
You could use the heterogeneous container pattern, but I would abandon the map idea and use a proper object.
Background
I'm currently working on an Android application which asks the user a question. At the moment I'm creating the modules for asking the questions. Right now I'm working on a topography module, which will be able to ask the user all kinds of questions about a certain country that will be shown to them.
Problem
For this module I will need a list of all the countries in the world. I currently have a Country class that has a String[] array that has all the countries English names in it (±200). I also want a few other properties in the Country class, such as their capitals, provinces and the translations for them. All of these properties should be selected from a predetermined list. This list should also be rather flexible, so that it in the future I can easily add new properties to them.
The problem I'm currently having is that I'm not quite sure how to create such a list. I've had a couple of ideas but all of them seem faulty, cumbersome or they just plain don't work in Java. Here is an example of a few of my ideas:
Create a multidimensional array that holds all the countries values which can then be easily selected with predefined indices. This is something that I often use when programming in PHP, because it can hold all kinds of different types. You can also define the keys (indices) of the array in PHP, but this doesn't work in Java.
Create an enum for all the countries and use the int associated with the specific country to select values from a capital/province array. This is a bit too cumbersome for my liking, it would require me to create an enormous array everytime I would want to add another property/question for the country (making a mess of the Country class in my opinion).
Create classes for all the properties I want Country to have. This has the advantage that I could expand on these classes further with more information (such as giving a Capital class properties such as: amount_of_residents), and has the advantage of perhaps creating a sophisticated translation class. I'm just wondering if this is the most efficient/logical way to proceed?
I feel that there should be some very nice solution for this problem I'm facing, but for the love of me I just can't figure it out. If you guys have any idea as what would be the best option (I'm currently leaning to option 3), or give me another solution to the problem that's more efficient, it would be greatly appreciated.
Note: I haven't added any code, because I didn't feel it would be necessary. If anyone would like to see some code I would be happy to provide it.
I believe you should go with the last approach, it should be something like the below sample code P.S
class Country {
String countryName;
String capital;
int noOfResidents;
List<String> provinces;
//getter & setters for them
public void setCountryName(String countryName)
{
this.countryName=countryName;
}
//And so on & forth
}
class SetCountryDetails {
public static void main(String[] args){
Map<String, Country> countryData = new HashMap<String, Country>();
//Using a map facilitates easier fetch for the countries. You can just
//provide the key of the country, for an instance to fetch the data for Germany
//just write countryData.get("Germany");
Country countryOne = new Country();
countryOne.setCountryName("Germany");
countryData.put("Germany", countryOne);
Country countryTwo = new Country();
countryOne.setCountryName("India");
countryData.put("India", countryTwo);
}
}
This approach enables you to add or delete a property to the Country class anytime without much hassle.
I'm not sure I totally understand what the issue really is. Basically you seem to have a domain object called Country that has a number of properties, and you seem to want to extend dynamically? Perhaps some code would help to solve your problem.
As per my understanding from your question, You need to use the list of Countries and respective properties of those Countries. And those properties need to be flexible in future to add/remove. For this you can maintain the list of countries and related properties in a property file or an XML file, which can be flexible in future to add/remove properties if required. If my understanding is wrong then make it clear for me. :)
I want to store three values in a 2D type in java. I know that we can use List and ArrayList for storing 1D values but I need to store more than one field in a specific record. For example i have to enter the details for multiple columns i.e. (1,1),(1,2),(1,3) for details such aaaa, bbbb, cccc for a person and store them in one single row(which may consist of values which are other than string type). It should run in a loop and once details of a person is stored, it should store (2,1),(2,2),(2,3) i.e. again for a new person. How to do that?
And later on, how to retrieve and send the complete set to database together? Please help..
What you might want to do is to create a class that holds all of the information you want to keep related to a single record if it represents a concrete thing and use the List and ArrayList to store those.
What I mean by concrete thing is something that has a finite set of information that will stay the same over each object.
Something like:
public class Person
{
String name;
Integer age;
// etc...
}
This gives you two advantages over using something like a 2D array. First, it will make reading your code easier, since instead of having to remember that arrayName[x][0] is whatever you decide the first field is, you can access it using something like listItem.attributeName. The second advantage is that you can abstract out any common datahandling tasks as class methods instead of having to bloat your main class with it.
I've got loads of the following to implement.
validateParameter(field_name, field_type, field_validationMessage, visibleBoolean);
Instead of having 50-60 of these in a row, is there some form of nested hashmap/4d array I can use to build it up and loop through them?
Whats the best approach for doing something like that?
Thanks!
EDIT: Was 4 items.
What you could do is create a new Class that holds three values. (The type, the boolean, and name, or the fourth value (you didn't list it)). Then, when creating the HashMap, all you have to do is call the method to get your three values. It may seem like more work, but all you would have to do is create a simple loop to go through all of the values you need. Since I don't know exactly what it is that you're trying to do, all I can do is provide an example of what I'm trying to do. Hope it applies to your problem.
Anyways, creating the Class to hold the three(or four) values you need.
For example,
Class Fields{
String field_name;
Integer field_type;
Boolean validationMessageVisible;
Fields(String name, Integer type, Boolean mv) {
// this.field_name = name;
this.field_type = type;
this.validationMessageVisible = mv;
}
Then put them in a HashMap somewhat like this:
HashMap map = new HashMap<String, Triple>();
map.put(LOCAL STRING FOR NAME OF FIELD, new Field(new Integer(YOUR INTEGER),new Boolean(YOUR BOOLEAN)));
NOTE: This is only going to work as long as these three or four values can all be stored together. For example if you need all of the values to be stored separately for whatever reason it may be, then this won't work. Only if they can be grouped together without it affecting the function of the program, that this will work.
This was a quick brainstorm. Not sure if it will work, but think along these lines and I believe it should work out for you.
You may have to make a few edits, but this should get you in the right direction
P.S. Sorry for it being so wordy, just tried to get as many details out as possible.
The other answer is close but you don't need a key in this case.
Just define a class to contain your three fields. Create a List or array of that class. Loop over the list or array calling the method for each combination.
The approach I'd use is to create a POJO (or some POJOs) to store the values as attributes and validate attribute by attribute.
Since many times you're going to have the same validation per attribute type (e.g. dates and numbers can be validated by range, strings can be validated to ensure they´re not null or empty, etc), you could just iterate on these attributes using reflection (or even better, using annotations).
If you need to validate on the POJO level, you can still reuse these attribute-level validators via composition, while you add more specific validations are you´re going up in the abstraction level (going up means basic attributes -> pojos -> pojos that contain other pojos -> etc).
Passing several basic types as parameters of the same method is not good because the parameters themselves don't tell much and you can easily exchange two parameters of the same type by accident in the method call.
This isn't a question that I am expecting a specific answer to since it is pretty broad. I'm teaching myself Java and am focusing specifically on dynamic memory allocation. Let's make a very oversimplified example: Say that I have a really basic data entry screen. So basic that all that happens is the user enters a series of first names, maybe for an employee directory or something. On my JFrame, I have a single JTextField control where these names are entered. The number of employees is known only at run time. The user enters a name and hits the enter key, which commits the name to memory and creates a new object to store the next name (silly, I know, but I'm trying to focus). Something like this (don't take this too literally - I obviously didn't compile this):
public class Employee {
String fName;
public void setName( String n ) {
fName = n;
}
};
public class JFrameEmp {
//blah, blah, blah
JTxtName.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
/* Handle the enter key */
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
/* Store name */
this.setName(JTxtName.getText());
/* Create New Object */
Employee next = new Employee();
}
};
}
}
Where I need help is on the last line. Even if this were to work, let's say that I wanted to print out a list of the names entered. In my approach, I see no way to uniquely identify each object (so that I can iterate through them).
Do I need to create an array to store these? But that has a fixed length and lives on the stack. I'd rather find a way to use the heap to allow for an open-ended list.
What should I be reading to learn how to do this? It must be a very common thing to do, but the books that I have don't seem to cover it.
Thanks. I hope that I have explained this well enough without going into too much detail.
It sounds like you want to store a List of Employees. Java provides dynamically sized array with its ArrayList class.
Here is an example:
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("Alice"));
employees.add(new Employee("Bob"));
System.out.println(employees.get(0)); // prints out Alice
You could use an array. You might find it useful to have a look at the Java Collections framework, in particular the page about the implementations.
But yes you will need to be adding the objects to some sort of data structure otherwise they will be getting cleaned up by the garbage collector after there is no valid reference to them.
It seems like you are looking for a data storage structure.
You could use a built in array, which is actually stored on the heap in java(the only issue is that you would have to keep track of size and reallocate when more space is needed).
A better option would be an ArrayList, which has built in add methods that automatically resize when needed.
You could also use a HashMap, which would allow to quickly search for your employees by name.