Dot notation for list of object in class - list

I have a "fixed list" in a class, I know all the objects that are in that list and I can refer to the objects through the names. The list is immutable, except for the parameters of every object contained in this list.
Something like this
class Object {
String name; // Know prior to build time
String color; // Can change
Object(this.name, this.color);
}
class MyClass {
List<Object> myList = [Object('apple', 'red'),
Object('banana', 'yellow'),
Object('mango', 'orange')];
}
I would like to access the members of the list like
final test = MyClass();
test.myList.apple.color = 'green'
Is there some "special list" that consent this type of access?
I tried using ENUM but they are not suitable for this problem.

A Map<String, String> would be better suited for what you are trying to do.
final colors = HashMap<String, String>();
colors['apple'] = 'green';

Related

how to pass all List<String> native methods to a List<Random>?

I'm new in Flutter(Dart) and I came across this problem. All lists of the type String naturally have the string methods like item.length, item.contains and so on. But when you create a random List type, it gets none of that. What is the recommended way of inherit all List properties to the custom one?
You probably didn't provide a list type and you can't see String methods.
void main() {
List<String> names = ['Dave', 'Ana', 'Robert'];
names.shuffle();
for(var name in names) {
print('name: $name, lenght: ${name.length}');
}
}

Want to check if object is in groovy list using .contains() or 'in'

import groovy.transform.EqualsAndHashCode;
#EqualsAndHashCode(includes="name")
class Activity {
public String name
public buildings = []
public rooms = [] as Set
Activity(name) {
this.name = name
}
}
thisActivity=new Activity("activity")
activityRegistry = []
// is false correct
activityRegistry.contains(thisActivity)
// add new item activity2
activityRegistry << new Activity("activity2")
// is true?????
activityRegistry.contains(thisActivity)
this code is pretty straight forward, I create an activityRegistry list, I compare empty list to object I created. naturally test fails. I create a new object on the fly using new that I insert into the list. I compare the list then to the first object created, which is not part of the list, and contains, or in passes. could someone shed some light on how? or why?
The AST "EqualsAndHashCode" only use 'properties' from the class. Properties, in groovy, are declared without a modifier ('public'), and getter/setter are automatically generated.
In your example, change public String name to String name.
See : What are 'properties' in Groovy?

C++ Nested JSON in Unreal Engine 4

I have a JSON object that I am getting from my server that looks something like this:
{
"state":"1",
"player1": {
"alias":"Player Name",
"ready":"0"
}
}
I am able to get the JSON, parse it into a FJsonObject, and retrieve any number or string in the first level of the JSON object using this code to serialize:
TSharedPtr<FJsonObject> JsonParsed;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(json);
if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
//Use JsonParsed
And this code to read strings:
FString AJSONContainer::getStringWithKey(FString key)
{
return storedJSON->GetStringField(key);
}
Side Note:
AJSONContainer is just an Actor class that I use to call these functions from Blueprints.
That's all fine and dandy, but when I try to read things from the second level, things don't work.
I wrote this code to get the next level down:
TSharedPtr<FJsonObject> nested = storedJSON->GetObjectField(key);
But all calls to get fields of nested return nothing.
nested->GetStringField(anotherKey); //Nothing
So, for example, with the above JSON, this:
TSharedPtr<FJsonObject> nested = storedJSON->GetObjectField("player1");
FString alias = nested->GetStringField("alias");
alias has no value when I print it to the console.
Am I doing something wrong? Why isn't the second-level JSON working?
Don't know if you got it sorted out, but I found a pretty nasty function that works for nested objects and, also, for arrays altogether. And it gives you a USTRUCT, so you don't have to use the functions that get values by Keys (I don't like them since they're very error prone). Instead, you'll have type safety!
FJsonObjectConverter::JsonObjectStringToUStruct
Here are the docs and another question answered on UE4 AnswerHub
Basically, you create the target USTRUCT (or USTRUCTs for nested JSONs), mark all properties with UPROPERTY, so Unreal knows their names, and use this function. It will copy the values by matchmaking them. It copies even the arrays! =D
Example
I'll call the JSON FString to be deserialized Json and it's structure is like the one below. It contains a nested object and an array, to make things interesting.
{
"nested" : {
"id" : "654asdf",
"name" : "The Name"
},
"foo" : "foobar",
"bar_arr" : [
{ "barfoo" : "asdf" },
{ "barfoo" : "qwer" }
]
}
Before converting, we need to create the USTRUCTs from inside out (so we can reference inner on the outer). Remember to always use F for struct names.
USTRUCT()
struct FNested
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FString id;
UPROPERTY()
FString name;
};
USTRUCT()
struct FBar
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FString barfoo;
};
USTRUCT()
struct FJsonData
{
GENERATED_USTRUCT_BODY()
UPROPERTY()
FNested nested;
UPROPERTY()
FString foo;
UPROPERTY()
TArray<FBar> bar_arr;
};
The conversion will go like this:
FJsonData JsonData;
FJsonObjectConverter::JsonObjectStringToUStruct<FJsonData>(
Json,
&JsonData,
0, 0);
Now, you are able to access all the properties as in standard C++ structs. Eg., to access one of the barfoos:
FString barfoo0 = JsonData.bar_arr[0].barfoo;
I have not tested it with int and float in the JSON, but since it copies even arrays, I believe that would work also.
for (auto currJsonValue = JsonObject->Values.CreateConstIterator(); currJsonValue; ++currJsonValue)
{
// Get the key name
const FString Name = (*currJsonValue).Key;
// Get the value as a FJsonValue object
TSharedPtr< FJsonValue > Value = (*currJsonValue).Value;
TSharedPtr<FJsonObject> JsonObjectIn = Value->AsObject();
}
The Json Object nested can be accessed by GetObjectField or the code I posted.
As I commented calling GetField<EJson::Object> instead of GetObjectField is the solution.
So this code will get your nested json:
TSharedPtr<FJsonValue> nested = storedJSON->GetField<EJson::Object>("player1");
TSharedPtr<FJsonObject> nestedParsed = nested->AsObject();
FString alias = nestedParsed->GetStringField("alias"); // alias == "Player Name"

Template Parameter Inheritance in C++

I haven't written C++ in a while, so I'm a bit rusty. If I have a class like this:
class JsonType{
protected:
map<string, JsonType>* objects;
}
and a class that inherits from that:
class JsonObject : public JsonType{
public:
JsonObject(){
this->objects = new map<string, JsonObject>();
}
}
why would I be getting a compiler error cannot convert...JsonObject...to...JsonType? Shouldn't that be legal, since JsonObject is a JsonType?
You can add JsonObject objects to the map, but the types do not match for initialization.
Edit: You have to initialize it as:
this->objects = new map<string, JsonType>();
But if you have either objects:
JsonType js = new JsonType();
or
JsonObject js2 = new JsonObject();
or
JsonType js3 = new JsonObject();
You can add any of these objects to the map initialized as above.
objects doesn't use JsonObject for its value_type, it uses JsonTypes.
In other words you are allocating the wrong kind of map to store into objects.

Sort a list based on URL parameter (or sort nested domain model in query)

I'm sure there is a way to do this, but I'm really stuck on this one.
I have a domain model that connects to entities Foo and Bar in a many-to-many-relationship. Now when I want to list all Foos to a certain Bar, I do the query and get a lot of FooBar objects. I iterate through these objects and add all Foos to a list.
Like so:
def fooBarRelations = FooBar.findAllByBar bar
def fooList = []
fooBarRelations.each { fooList.add it.foo }
How can I sort the fooList based upon the parameters a g:sortableColumn adds to the url namely sort (the field to sort) and order.
I know you can pass the parameters to the query directly but I think this is not possible in my case?
So how can I either
Make one query without list iterating so I can pass in the sorting parameters OR
Sort my custom list based upon the sorting parameters?
Addition 1 (03/25/2012)
If I could to this ...
def fooBarRelations = FooBar.findAllByBar bar, [sort: 'foo.' + params.sort, order: params.order]
... the problem would be solved. But passing this to the query does not have any effect on the output. Is there any way I can sort a query by a sub-property?
If you really can't sort within the query itself. Then you need a list of lists.
List<List<Fields>> mylist;// where List<Fields> is a lists of the fields.
Then use a Comparator to sort your List> by the desired filed. Say your desired field is at index 3:
new Compare(List<Fields> L1, List<Fields> L2){
if(L1.get(3)>L2.get(3))
return -1;//etc.
UPATE BASED ON COMMENT:
say your entity is as follows
public class Entity{
String name, address, school;
Integer bankaccount;
//etc...
}
Then
public class WhereISort{
List<Entity> myList;
String mysorter;//mysorter can be declared here as static final
public WhereISort(){//maybe pass list in here or whatever
}
public Response myWebService(params..., String sorter){
mysorter=sorter;//mysorter can be declared here as static final
Collections.sort(myList, new Comparator() {
public int compare(Entity e1, Entity e2) {
if(mysorter.equalsIgnoreCase("name")){
return e1.getName().compareToIgnoreCase(e1.getName());
}else if(mysorter.equalsIgnoreCase("bankaccount")){
//your code here, etc.
}
}
});
}
}
Of course, the main point is using "mysorter" and the inner class "Comparator" to sort