Quickest way to lookup a object - java

Suppose you have a list of Sunglasses objects where there are ...
4 attributes, color, shape, style and brand.
no identical ones; the combination of 4 attributes always different
What is the fastest way to retrieve them?
I think:
Override the hashcode() method in the Sunglasses class (should be unique because none of them are identical).
Then using each object's hashcode as key, object itself as value, put them into a Hashmap
Suppose I remember exactly what color shape and style and brand of a glass I want to
get,
I apply them with the hashcode method I have implemented.
then get it from the hashmap, this should give me contants time O(1) retrieval.
Problem is what if I only know the color. How do I get a list of all glasses with the same color?

Build a HashMap<Color,Collection<Glasses>> in addition to your other data structures.
This map essentially servers as an index on the Color attribute.
Whenever you add or remove glasses from your other data structures, make sure to update this color index as well.

Create a value class to hold the 4 attributes, and create hashcode and equals methods that use all the fields.
Use the class as a field of sunglasses instead of having separate fields (that way if you change it to add another field, it changes everywhere)
Use a hash map of value class --> sunglasses and when querying, build a value object at use map.get(value)

Related

generic java structure to store multiple object types and keys defined

I am looking to see whats out there in collections in any java framework like apache or guava that will let me handle the below. I am also open to consider any custom implementations if required
Basically I have
Inventory object , the inventory number field will help identify a
unique inventory object
Order object the order number field will
help identify a unique order
OrderItem Object, the order number and
item number fields will help identify a unique order (the key here
is composite)
I can have more objects come in later on with different attributes and having composite key types. Also I dont want to put the orderItem inside the order object
Basically I am looking to see if there is a elegant way to build a generic structure where in I can define the keys that will help identify a object and retrieve the object dynamically using the key? I should be able to specify composite key types as well.
structure.put(invKey, inventory);
structure.put(orderKey, order);
structure.put(orderItemKey, orderItem) (the key here is composite of two attributes)

which collection/ data structure can handle key, value, value

I have been using a HashMap which handles key / value pairs. But, now i need to handle key: value , value. Is it possible to have one key with 2 values ?
can you recommend a data structure/collection or strategy for me?
Yes you can, assuming this is c++, you can have
std::unordered_map<key, std::pair<value, value>>;
You can make the std::pair whatever type you'd like them to be.
What'd make more sense to do is to make an object to hold your two values, like HashMap<KeyType, ContainerObject> map.
In container object, you can use something like a list, or your own defined object that's made to just hold whatever two values you need. This way, you can use the HashMap and just access whatever values you need through the object that holds them.

4 Key Value HashMap? Array? Best Approach?

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.

Java Domain Classes fill with data

I have some domain classes and i want to init and fill those classes with sample hardcode data , is there any method which i can fill data with any framework ?
For Example : List<Customer> should be filled with some mock data
Consider maintaining your test data in a JSON structure, and use a framework (e.g. google-gson) to deserialize the data into value objects.
If you wish to auto-generate random data, you might want to look into something like Quickcheck, which seems to be Java's equivalent of the .NET framework Autofixture.
As #ipavlic wrote, you might make your constructor generate some random data when the object is created.
You may store the data in a DB or a simple text file and read it from there when you fill your list.
You may combine aproach 1 and 2 and store possible field values in a file or somewhere else and fill the Object fields with these randomly chosen predefined values.
If you want fill list of Customer, there is this method Collections.fill(java.util.List, T) to fill list. This method replace current objects in list. If list is empty it won't fill.
You can put your hard-coded data in a constructor.
If it's mocking frameworks that you are after (as you indicate in comments), then take a look at e.g. Mockito.

java dynamic attributes table

I am developing a java application which needs a special component for dynamic attributes. The arguments are serialized (using JSON) and stored in a database and then deserialized at runtime. All attributes are displayed in a JTable with 3 columns (attribute name, attribute type and attribute value) and stored in a hashmap.
I have currently two problems to solve:
The hashmap can also store objects and the objects can be set to null. And if set to null i dont know which class they belong to. How could i store objects even if they are null and known which class they belong to? Do i need to wrap each object in a class that will holds the class of the stored object?
The objects are deserialized from json at runtime. The problem with this is that there are many different types of objects and i don't actually know all object types that will be stored in the hashmap. So i am looking for a way to dynamicly deserialize objects.. Is there such a way? Would i have to store the class of the object in the serialized json string?
Thanks!
Take a look to the Null Object Pattern. You can use an extra class to represent a Null instance of your type and still could contain information about itself.
There is something called a Class Token, Which is the use of Class objects as keys for heterogeneous containers. Take a look to Effective Java By Joshua Bloch, Item 29. I'm not sure how this approach could work for you since you may have many instances of the same type but I leave it as a reference.
First of all, can you motivate why you use JSON serialization for your attributes ?
This method is disadvantageous in many ways in my opinion, it can cause problems with database search and indexing, make database viewing painful and caus unnecessary code in your application. These problems can be not an issue, it depends how you want to use your attributes.
My solution for situation like these is simple table containing columns like:
id - int
attribute_name - varchar
And then add columns for each supported data type:
string_value - varchar
integer_value - int
date_value - date
... and any other types you want.
This design allow for supreme performance using simple and typesafe ORM mapping without any serialization or other boilerplate. It can store values of any type, you just set correct column for attribute type, leaving all other with null. You can simulate null value by using null in all data columns. Indexing and searching also becomes a piece of cake.

Categories

Resources