Instance an object in an array which is an attribute of antoher object - arrays

What is the correct way of declaring an instance of an object which is part of an array that is an attribute of another object? I have a class called ingrediente which is quite simple. It looks like this:
public class ingrediente{
public int cantidad;
public String nombre;
public int fechaDeCaducidad;}
I have another class called receta which has an array of ingrediente objects:
public class receta{
ingrediente [] ingredientes;
String preparacion;
String nombreReceta;}
I want to give values to the attributes of an ingrediente object which is part of the array ingredientes in an instance of the receta class. I'm not even sure if I have to declare the ingrediente object before giving values to it, but the code doesn't work (although it doesn't show syntax errors) wether I do it or not. The code looks like this:
recetas [CONTADORRECETAS].ingredientes [CONTADORINGREDIENTES2] = new ingrediente ();
recetas [CONTADORRECETAS].ingredientes [CONTADORINGREDIENTES2].nombre = TEMP2;
Can anybody tell me what I'm doing wrong? The code is inside a try and it throws java.lang.NullPointerException on those lines (on the first one if I include it and on second one if I don't). The value of the attribute doesn't get asigned. Variable TEMP2 is previously declarated and is of the correct type.

Related

Dynamic Array as Class Property in VBScript

I am very new to VBScript, and not entirely sure if what I am doing is right.
I want to create a structure to hold onto a string and then an array of strings. The array of string will be dynamic, as I do not know how many entries are going to be in that list.
I have the following:
Class ExportMappings
Private _process_definition
Private _export_mappings : Set _export_mappings = CreateObject("System.Collection.ArrayList")
Public Property Let ProcessDefinition(procDef)
_process_definition= procDef
End Property
Public Property Get ProcessDefinition()
ProcessDefinition = _process_definition
End Property
Public Property Let ExportMappings(export)
_export_mappings = export
End Property
Public Sub AddMapping(map)
_export_mappings.Add map
End Sub
End Class
First, I am not sure if I declared the _export_mapping array properly.
Secondly, I do not know if I need a constructor to initialize my _export_mappings to an initial size. If so, I do not know how I would do that.
Lastly, my get and set methods for ExportMapping, I am not sure if that will work.
I would try to run it through a debugger, but the software I am using does not have the best debugger, and usually gives me a very vague description of what is wrong.
First things first:
VBScript variable names can't start with _; you can 'legalize' invalid names by putting them in [], but for starters I wouldn't do this
Code in Classes is allowed in methods only; your Private _export_mappings : Set _export_mappings = CreateObject("System.Collection.ArrayList") is invalid
After these changes, your code should compile. If you add code showing how you'd like to use this class, I'm willing to talk about second things (maybe tomorrow).

c# returning arrays via properties

Id like to firstly apologise for what may appear to be a stupid question but im confused regarding the following.
Im writting a class library which will not be running on the UI thread. Inside the CL i need an array which im going populate with data received from a stored procedure call. I then need to pass this data back to the UI thread via an event.
Originally i was going to write the following.
public class ColumnInformation
{
public string[] columnHeaderNames;
public string[] columnDataTypes;
}
but im pretty sure that would be frowned upon and i instead should be using properties.
public class ColumnInformation
{
public string[] columnHeaderNames {get; set;}
public string[] columnDataTypes {get; set;}
}
but then i came across the following.
MSDN
so am i correct in assuming that i should actually declare this as follows:
public class ColumnInformation
{
private string[] _columnHeaderNames;
public Names(string[] headerNames)
{
_columnHeaderNames = headerNames;
}
public string[] GetNames()
{
// Need to return a clone of the array so that consumers
// of this library cannot change its contents
return (string[])_columnHeaderNames.Clone();
}
}
Thanks for your time.
If your concern is the guideline CA1819: Properties should not return arrays,
It will be same whether you are exposing Array as a Public Field, or Property (making readonly does not matter here). Once your original Array is exposed, its content can be modified.
To avoid this, as the link suggest, make Field private, and return Clone from the Getter.
However major concern is that there may be multiple copies of your array if retrieved many times. It is not good for performance and synchronization.
Better solution is ReadOnlyCollection.
Using ReadOnlyCollection, you can expose the collection as read only which cannot be modified. Also any changes to underlying collection will be reflected.

What does static refer to being "stuck" to?

I'm trying to give myself a mapped idea of the word static (using my current noun definition of static, not having a good understanding of the adjective definition), but it would seem that non-static variables and methods actually are "stuck" (or better said referencing/referring) to objects/instances. So what is the terminology static actually describing about the declared methods/variables?
The words "static" and "dynamic" are frequently used as opposites in programming terminology.
Something that is dynamic is something that changes; in the context of a class, it is something that takes on different values or behaviors with each instance (object).
Something that is static does not change; it is in stasis. So a static variable of a class does not take on different values with each instance.
Static electricity doesn't move; it is stuck in one place, on your socks. Dynamic electricity, in motion in a wire, can do much more powerful things.
I think this question here provides a very detailed answer: What is "static"?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.

Convert String into an object instance name

I'm trying to turn an string into an instance name.
stage.focus = ["box_"+[i+1]];
this gives me back = box_2;
but I need it to be an object not a string.
In as2 I could use eval. How do I do it in as3?
The correct syntax is:
this["box_"+(i+1)]
For example if you would like to call the function "start" in your main class, you'd do it this way:
this["start"]();
Same thing goes for variables. Since all classes are a subclass of Object you can retrieve their variables like you would with an ordinary object. A class like this:
package{
import flash.display.Sprite;
public class Main extends Sprite{
public var button:Sprite;
public function Main(){
trace(this["button"]);
}
}
}
Would output:
[object Sprite]
If you want to access a member of the current class, the answers already given will work. But if the instance you are looking isn't part of the class, you are out of luck.
For example:
private function foo():void {
var box_2:Sprite;
trace(this["box_"+(i+1)]);
}
Won't work, because box_2 isn't a part of the class. In that case, it is highly recommended to use an array.
If you want to access a DisplayObject (for example, a Sprite or a MovieClip) you also can use getChildByName. But in that case, box_2 will be the name of the object, instead of the name of the variable. You set the name like
var box:Sprite;
box.name = "box_2";
But again, I recommend an array.

GWT JsArray of self, recursive object array

I am building a tree structure which an object references itself in like so:
public class ProjectObjectOL extends JavaScriptObject {
protected ProjectObjectOL() { }
public final native boolean getStatus() /*-{ return this.status; }-*/;
public final native String getError() /*-{ return this.error_message; }-*/;
public final native JsArray<ProjectObjectOL> getChildren() /*-{ this.children; }-*/;
}
My problem is that I can't seem to get the children of the object. I've tested it out, and I'm quite sure the JSON structure being passed back consists of an object that contains an array of children of that type which can contain children, etc.
...but when trying to access even the simplest information about the children, the length of the array, it returns 0 every time. I've tried with no success to figure out what it's doing wrong, all the other data returns fine, but this one piece will NOT retrieve the children. Here is an example of how I might (directly) access the length for testing:
JSONObject oResults = (JSONObject) JSONParser.parse(response.getText());
ProjectListOL testoutputOL = oResults.isObject().getJavaScriptObject().cast();
ProjectObjectOL testObject = testoutputOL.getProjectList().get(1);
Window.alert(testObject.getChildren().length()+"");
A ProjectListOL contains an array of ProjectObjectOLs. In the example above I simply grabbed the one I KNOW has children. I'm using ColdFusion for the backend that returns the JSON object. Once again, I have output this object multiple times, both in GWT and outside (directly dumping the JSON object from the file) verifying that the object is indeed set up how I expect it to be set up.
I missed an obvious mistake:
public final native JsArray<ProjectObjectOL> getChildren() /*-{ this.children; }-*/;
OOPS:
public final native JsArray<ProjectObjectOL> getChildren() /*-{ **return** this.children; }-*/;

Resources