I have one java class like below:
public class Location
{
public String city;
public String state;
public String country;
public enum type{Beach,Forest,Hills,Desert};
}
as above type member is enum type and i want to assign multiple enum values to type proprties like one Location object has more then one type properties like it has Hills as well as Forest.
then how should i have to do it?
where to declare enum and how to assign to enum values to one object.
Is it possible to assign to enum values one object without using array?
You need a Collection to store a variable number of values. Since you don't want to have duplicates use a Set. For enums exist java.util.EnumSet which has a compact and efficient way to store multiple values:
public class Location
{
public enum Type {Beach,Forest,Hills,Desert};
public String city;
public String state;
public String country;
public EnumSet<Type> types = EnumSet.noneOf(Type.class); // start with empty set
}
You can store them in class variables:
private final Terrain first = Terrain.BEACH;
private final Terrain second = Terrain.DESERT;
Similarly, you can store them in a collection of terrains if that is more appropriate:
private final Set<Terrain> terrains = new HashSet<>(Arrays.asList(Terrain.BEACH, Terrain.DESERT));
Or use an EnumSet:
private final EnumSet<Terrain> terrains = EnumSet.of(Terrain.BEACH, Terrain.DESERT);
On a side note, it is more conventional to declare enumerations in their own file, I have assumed that it will be called Terrain. Also, constants (thus also enum values) are usually written in capital letters.
Related
This question already has answers here:
Java: Getter and setter faster than direct access?
(3 answers)
Closed last year.
I have the below class with around 200 variables.
public class BaseDataDTO {
private CSVRecord rawData;
private List<InquiriesDataDTO> inquiriesData;
private ListTradesDataDTO> tradesData;
private List<CollectionsDataDTO> collectionsData;
private Long applicantId;
//cvv attributes
public String adg001;
private String adg002;
private String adg003;
private String adg004;
private String apg05;
-
-
private String apg199;
}
From a different class, I would like to access the instance variables through the variable names, is it possible to do? I need to do this since I need compare some another response with the instance variable of that class through a Map key. How can I achieve some thing to the effect of the text in bold below?
I do not want to use getter methods here since it is in a for loop for 200 times.
BaseDataDTO baseData = CSVParser.parseBaseData(fileName);
Map<String, String> attributes = fileLoader.withName("attributes.json").jsonToObject(Map.class);
for (String key : attributes.keySet()) {
String responseValue = response.getModelScores().get(0).getScoringInput().get("function_input").get(key).asText();
String expValue = baseData.get(key));
AssertEquals(responseValue, expValue);
}
Create a BaseDataDTO from your Map and check for equality via equals.
Never ever access object fields by their name string, unless you are writing low level libraries like parsers.
Accessing fields by name is done via Reflection:
String expValue = (String) BaseDataDTO.class.getDeclaredField(key).get(baseData)
Note that stuff like this is at least an order of magnitude slower than using a getter.
This topic is a little bit more complicated then in a title.
Let's assume that we want to model an entity. This is something like KYC informations (name,surname, address etc). I could model this in simple way in one class like:
public class KYCInfo {
private KYCInfoType type;
private String firstName;
private String lastName;
private Address personalAddress;
private Address buisnessAddress;
private String country;
private String state;
private LocalDate dateOfBirth;
private String personalIdNumber;
}
As you see in code above, this KYC can be of different type. Actually two values can be in that type - buisness and individual. For business, buisnessAddress field is required, for individual personalIdNumber is required. Additionaly some of this fields will be required depending on country field. State field is for US but not for European countries. Placing all of this fields in one class seems to be inappropriate - every instance, depending on field would have a lot of null values. I could create separate classes for BuisnessKYCInfo and IndividualKYCInfo for example. But then I would have some duplications in fields (lets say that firstName,lastName and some other fields are the same for both classes). I could create some abstraction with common fields. Like :
public abstract class KYCInfo {
private String firstName;
private String lastName;
}
Now imagine that this is a simple DTO class and in some moment i process it somehow in a method processKYCInfo(). When I have two classes BuisnessKYCInfoandIndividualKYCInfothen I would need to have two methods
``processKYCInfo(BuisnessKYCInfo kycInfo) and processKYCInfo(IndividualKYCInfo kycInfo). This method will do the same operation, but will collect info from different fields. Now imagine, that you have more type than individual or buissness. Or as i wrote before, additional 'type' comes in like country. Now I would need to have 25 countries, some of them have fields specific only for that country. With the same approach like before I would have 25 methods doing almost the same. This also seems to be inappropriate. What other option do I have to model this ? Maybe some data structure, maybe some Map ? What is best approach of doing this ? How can I do it in more generic way ?
Here is my approach:
Following is the data structure I'll use:-
public class KYCInfo {
private KYCInfoType type;
private Map<String, String> name;
private Map<String, String> address;
private String country;
private String state;
private LocalDate dateOfBirth;
private String personalIdNumber;
public KYCInfo(){
name = new HashMap<>();
address = new HashMap<>();
}
So what is the advantage of this approach:-
Instead of creating multiple same type of attributes, create a family. e.g. name will be the family for 'firstName', 'middleName', 'lastName'. The pair will be like <'firstName','Bob'> ,<'lastName','Marley'> etc. In this way you can have either of them or all of them.
Similarly for other attributes like address. The pair can be like <'personalAddress','some value'> , <'buisnessAddress','some value'>
Each record can have their own categories for a family.
I'm a java beginner and have a question concerning how to best structure a cooking program.
I have a class called Ingredient, this class currently looks like this:
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor,String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
I want to initialize several objects (about 40) with certain values as instance variables and save them in a Map, for example
Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)");
Later on I want to retrieve all these objects in the form of a Map/HashMap in a different class.
I'm not sure how to proceed best, initialize all these objects in the Ingredient class itself or provide a method that initializes it or would it be better to create an super class (AllIngredients or something like that?) that has a Map with Ingredients as instance variables?
Happy for any suggestions, thanks in advance :)
Please do not initialize all these objects in the Ingredient class itself. That would be a bad practice for oops.
Just think your class is a template from which you create copies(objects) with different values for attributes. In real world if your class represent model for a toy plane which you would use to create multiple toy planes but each bearing different name and color then think how such a system would be designed. You will have a model(class). Then a system(another class) for getting required color and name from different selection of colors and names present(like in database,files,property file ) etc.
Regarding your situation .
If predetermined values store the values in a text file,properties file,database,constants in class etc depending on the sensitivity of the data.
Create Ingredient class with constructors
Create a class which will have methods to initialize Ingredient class using predetermined values,update the values if required,save the values to text file -database etc and in your case return as map .
Also check the links below
http://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm
http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
Sounds to me like you are looking for a static Map.
public class Ingredient {
private String identifier;
private double ingredientFactor;
private String titleInterface;
public Ingredient(String identifier, double ingredientFactor, String titleInterface) {
this.identifier = identifier;
this.ingredientFactor = ingredientFactor;
this.titleInterface = titleInterface;
}
static Map<String, Ingredient> allIngredients = new HashMap<String, Ingredient>();
static {
// Build my main set.
allIngredients.put("Almonds (ground)", new Ingredient("Almonds (ground)", 0.7185, "Almonds (ground)"));
}
}
Hope you don't mind I'm asking a newbie question about the use of iterator for a arrayList / List.
I have a Building Class with a few data members:
public Building() {
private String buildingName;
private String buildingType;
private double width;
private double length;
private String managerName;
....
}
I've already set toString() as follow to access the name String and I'm NOT allowed to change toString to return a different data member.
public String toString() {
return buildingName;
}
I've created a bunch of building objects in the Building class by loading a building.xml file, and I've used iterator to create an array/list of buildingNames to be viewed in a swing ComboBox (but let's ignore those swing component below and focus on the just the logics):
// Create building combo box model.
buildingComboBoxModel = new DefaultComboBoxModel<Building>();
buildingsCache = new ArrayList<Building>(buildings);
Iterator<Building> i = buildingsCache.iterator();
while (i.hasNext()) buildingComboBoxModel.addElement(i.next());
// Create building list.
buildingComboBox = new JComboBoxMW<Building>(buildingComboBoxModel);
buildingComboBox.addActionListener(this);
buildingComboBox.setMaximumRowCount(10);
buildingSelectPanel.add(buildingComboBox);
How many ways do can you think of and how in putting together an list of buildingType using iterator without significant code changes?
If I need to modify some of the buildingType Strings in some situations by adding a String to it,
say in one building,
String buildingName = "Adam's Place";
String buildingType = "Greenhouse";
[post edit]
e.g. I need to change buildingType to "Greenhouse Type 1" for "Adam's Place" and change another building's buildingType to "Greenhouse Type 2"
Can it be done using iterator and how?
If not, other ways are welcome
Thanks in advance!
There is no special way for handling objects read from an iterator. If the only changes needed are just setting different values to the members of the Building class, this can be done the standard way, i.e. by adding member setter functions.
For example, to modify the buildingType at any time, a setBuildingType() method is needed:
public class Building {
private String buildingName;
private String buildingType;
private double width;
private double length;
private String managerName;
....
public void setBuildingType(String buildingType) {
this.buildingType = buildingType;
}
}
Given the above, the iterator-based code can be modified as follows:
Iterator<Building> i = buildingsCache.iterator();
while (i.hasNext()) {
Building b = i.next();
b.setBuildingType("Whatever type");
buildingComboBoxModel.addElement(b);
}
How will I be able to retrieve the value of a variable which has a dynamic name
For Example I have list of constants
public class Constant{
public static final String S_R = "Standard(240)";
public static final String S_W = "Standard(180)";
public static final String L_R = "Large(360)";
public static final String L_W = "Large(280)";
}
Based on database I build a variable name
String varName = "S" + "_" +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.
You can use a Map<String, String> and locate the value by its key.
Even better, you can have an enum:
public enum Foo {
S_R("Standard", 240),
S_W("Standard", 180),...;
private String type;
private String duration;
// constructor and getters
}
And then call Foo.valueOf(name)
(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)
If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.