Using variables as names for other variables in Java - java

Alright, I am not completely sure that I worded the title right, but I want to use an int variable to define another int to go through a method. In other words, I want to be able to have the int/name/thingy variable go through a ++ statement, and then the next variable would go through the method. Is this possible?

An int array might solve your problem. The array stores your ints ("variables"), another one runs throught the index (your ++ operation):
int[] values = loadValuesInArray(); // some magic to get the populated array
for (int i = 0; i < values.length; i++) {
myMagicMethod(values[i]); // calling the method with int values
}
If you need named variables, then you can use a map:
Map<String, Integer> variables = new HashMap<String, Integer>();
variables.put("a", 1);
variables.put("b", -10);
variables.put("c", 25);
myMagicMethod(variables.get("b")); // calls method with value from "variable" b

You can use reflection.
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
http://www.java2s.com/Tutorial/Java/0125__Reflection/Catalog0125__Reflection.htm
or see to have an idea.
Setting variables by name in Java

You almost certainly want to be using something like a Map or List (essentially a dense map with a small positive int key).

If you don't need to create a new variable with a name, stored in another variable, then reflection is a way to go.
String varName = "x";
Point2D point = new Point(15, 2);
Integer val = (Integer)Point.class.getDeclaredField(varName).get(point);
assert val == 15;

You say "I want to use an int variable to define another int" do you mean something like
int a = 0; //declare a new variable a of type int and assign it to zero
a b = 0; //declare a new variable b of type a which is an int and assign it to zero
From what you said, that is what it appears you are saying. If that is the case, I do not think you can do that. My memory says that there is a method that allows you to determine the type of an object, but to use that as a declaration of another variable... I don't know if you can do that.

Related

use ints for prop.setProperty()

i'm trying to do a configurations file from an array of objects, where the properties are taken from a range of getters.
eg
prop.setProperty("Name", bugs[0].getName());
prop.setProperty("Species", bugs[0].getSpecies());
When i try, for example
prop.setProperty("Energy", bugs[0].getEnergy());
it says
The method setProperty(String, String) in the type Properties is not
applicable for the arguments (String, int)
How would I do method of setProperty(String, Int)?
EDIT*
Also, How do i write for an array of the objects, looping bugs[i] doesn't seem to work either.
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name", bugs[i].getName());
prop.setProperty("Species", bugs[i].getSpecies());
prop.setProperty("X", String.valueOf(bugs[i].getX()));
prop.setProperty("Y", String.valueOf(bugs[i].getY()));
prop.setProperty("Energy", String.valueOf(bugs[i].getEnergy()));
prop.setProperty("Symbol", String.valueOf(bugs[i].getId()));
}
// save properties to project root folder
prop.store(output, null);
How would i make it show the values for all the bugs, its only showing the last one?
bugs[0].getEnergy() is giving integer value to you and you are setting integer value insted of string that why exception came in your code.
Try
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
For second part of Question :
How do i write for an array of the objects, looping bugs[i] doesn't
seem to work either.
Your loop showing last value because your key of property is same, you are not changing the key assigning all values to same key so it is giving you last value.
Try something , It will create new keys
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name"+i, bugs[i].getName());
prop.setProperty("Species"+i, bugs[i].getSpecies());
}
Mainly you can do this in two ways:
First way:
Overloading the setProperty(); metod. As it seems you decleared this method some where like this:
public void setProperty(String s1, String s2) {
// Doing some operations
}
Now, you can overload another method with the same name, but different signature to handle another kind of arguments (String - int), like this:
public void setProperty(String s1, int value) {
// Doing some operations suitable for this kind of method
}
Second way:
You can also easily convert the value of given integer to the string, by String.valueOf(); method, like this:
prop.setProperty("Energy", String.valueOf(bugs[0].getEnergy()));
EDITED:
In the loop you entered here, you're overwriting the values of prop object properties every time you loop through for.
First time the name of prop will be the bugs[0].getName(). In the next time, the last value will be deleted and bugs[1].getName() replaces it.
So if you want to store all of bugs array properties, you need an array of prop like objects (I don't know whats the type of prop but I assume it's Prop). So you need to write something like this:
Prop[] props = new Prop[bugs.length];
And then set properties of it's elements.
Also if you want to store all of properties in one object, you have to change the given key to setProperty(String, Int) method (as the String). So you can do something like this:
for (int i = 0; i < bugs.length; i++) {
prop.setProperty("Name " + i, bugs[i].getName());
prop.setProperty("Species " + i, bugs[i].getSpecies());
// An so
}
prop.store(output, null);

Change the value of instance without changing the other instance

For those who had read my first question, I think I found where the problem is. The problem is in the mutate method and especially in this instruction:
Chromosom ch=new Chromosom(); // Chromosom is a class who use hash table
Chromosom k= new Chromosom(); // Class chromosom extends hashmap <integer,parc>
k.initialise();
for(int i=0;i<l.size();i++) ch.put(i,k.get(i)); // in this instruction i think
And this is the constructor of Chromosom:
public Chromosom(){ // construct a blank chromosom
super();
this.identifiant = 0;
NbEquipeExterne = 0;
NbEquipeInterne = 0;
CoutMinimal = 0;
CoutMensuel = 0;
}
When I change the values of ch, the values of k change too?
How can I pass the k's values to ch by copy and not by reference?
First of all Java is always pass-by-value. or rather pass-by-copy-of-the-variable-value not pass by reference. You might be changing objects of Chromosom with k in the constructor.
No danger, both ch and k are separate objects.
Furthermore you can do
ch.putAll(k);
which is a nice short-cut to remember.
Caveat
If the values of the maps are stateful objects (having mutable fields to contain some changing info), then changing that field would change the field of the simgle value object in both tables.
BitSet bits = k.get(i);
bits.set(3);
// Now ch.get(i) being the same object, also has bit 3 set.
If a class has a static field, then that field is once per class, a single instance. So you could have in say Chromosome:
static String copyright;
Chromosome.copyright = "All rights reserved"; // Clearest style
k.copyright = "All rights given to the community";
ch.copyright = "MIT license";
And you would have dealt with the same single variable, with vaklue "MIT license".
About Java
A nice design decision was made in java:
If you pass a variable to a function/method, the object/value will be passed. It may never happen that the variable itself gets an other object/value. (Not the address of the variable is passed.) Java has pass-by-value, no pass-by-reference.

Why can the immutable class Integer have its value reset?

I was reading earlier that wrapper classes are all immutable. Immutable means that the value cannot be changed. Below I tried this simple example that can just be pasted in to any main method. first I create a Integer that wraps the value five. Immutable means that they cannot be changed so why can I set I to 89. I think that it is because it changes where (I) points to but I am not certain why this is the case.
In my next little example i create an Integer of x which will throw an error if I try and change it. The x seems to be immutable in this specific case but not in the case of the (i) variable.
It seems that I can change the value of (i) whenever I want to so in reality Integer without the final keyword is not immutable???? If i can be set to 89 then to me this seems that the variable can be changed.
I have read other post on this and I still am not certain why i can be changed to another variable. Also in writing code what is the best way to declare primitive types. Why not use the wrapper classes all of the time to create variables.
int y = 5;
Integer i = new Integer(y);
i = 89;
final Integer x = Integer.valueOf(5);
System.out.println("Integer:(i) " + i.intValue());
System.out.println("Integer:(i) " + i.byteValue());
System.out.println("Integer:(x) " + x.intValue());;
System.out.println("Integer:(x) " + x.byteValue());;
i = i - 5;
Using all wrapper classes to declare variables: (Would this be better than declaring these variable with the primitive variable types)
Integer a = new integer(MyNewValue);
Integer b = new integer(MyNewValue);
Integer c = new integer(MyNewValue);
Integer d = new integer(MyNewValue);
Float fa = new integer(MyNewValue);
You are conflating two things: changing the value of an "object" itself and changing the object a reference points to. Saying i = 89 just points the variable i to a new object; it doesn't change the Integer object which originally was pointed to by i.
Pre-pending variable declarations with final just ensures that reassigned is prohibited, it is in no way a declaration of the mutability/immutability of the object it points to. Maybe off-topic, but I personally think the article Java is Pass-by-Value, Dammit! is a good read.
When you call i = 89;, your not changing the value of the Integer object stored in memory. Instead, you're assigning a brand new int with value 89 to i. So the immutable rule isn't being broken.
Remember that i is simply a reference that points to the Integer, not the actual Integer itself.
Yes, it does look like the integer is changing, but all that is happening on line 3 is its being converted to i = new Integer(89) by the compiler. If you wanted to see, you could do
Integer i1 = i;
i = 83;
println(i); \\ prints out the original value 5
println(i1); \\ prints out a new value, 83
When you declare something as final, you cannot change the definition of the variable, though you can still mutate anything inside it. JavaRanch has a very nice analogy to help
You should not use wrapper objects when you can avoid it because they are a small amount less efficient to than primitives and take up a few extra bytes.

Variable declaration with its name containing value from loop

i am php developer just started at java i want to declare dynamic variables inside a loop and for that i have to append the loop value to varaible name this is what i want .
I would like to make statement like this
for (i=1; i<6; i++)
{
String new_variable_ + i;
}
the above code does not work in java how to do it ?
what you are trying to do is not possible in java ... this language is
not that lose like php..its a type strict language
Variable declarations are declared to be static identifiers and cannot contain any computed values in java (and i venture to say this would be true in any statically typed language).
You say you can't find an associative array. Have you seen the java.util.Map interface (and it's implementations)? It is by definition an associative array:
Wikipedia: In computer science, an associative array, map, or dictionary is an abstract data type composed of a collection of (key,value) pairs, such that each possible key appears at most once in the collection.
Like I said in the comment, there's no dynamic variable in Java. At best you can do this:
HashMap variableMap = new HashMap<String,String>();
for (int i = 1; i < 6; i++) {
variableMap.put("new_variable_" + i, "some variable value");
}
Then to access them, you do:
String value = variableMap.get("new_variable_2");
Or to update it, you do:
variableMap.put("new_variable_2", "new value");
If you just want to use a string version of i within the loop, you need:
for (int i=1; i<6; i++)
{
String new_variable_ = "" + i;
//use new_variable here.
}
If you're looking for something different, I'll need some more details. Good luck!

Simulating pass by reference for an array reference (i.e. a reference to a reference) in Java

I was wondering, in java, is it possible to in anyway, simulate pass by reference for an array? Yes, I know the language doesn't support it, but is there anyway I can do it. Say, for example, I want to create a method that reverses the order of all the elements in an array. (I know that this code snippet isn't the best example, as there is a better algorithms to do this, but this is a good example of the type of thing I want to do for more complex problems).
Currently, I need to make a class like this:
public static void reverse(Object[] arr) {
Object[] tmpArr = new Object[arr.length];
count = arr.length - 1;
for(Object i : arr)
tmpArr[count--] = i;
// I would like to do arr = tmpArr, but that will only make the shallow
// reference tmpArr, I would like to actually change the pointer they passed in
// Not just the values in the array, so I have to do this:
for(Object i : tmpArr)
arr[count++] = i;
return;
}
Yes, I know that I could just swap the values until I get to the middle, and it would be much more efficient, but for other, more complex purposes, is there anyway that I can manipulate the actual pointer?
Again, thank you.
is there anyway that I can manipulate the actual pointer?
Java does not pass by reference, so you can't directly manipulate the original pointer. As you've found out, Java passes everything by value. You can't pass a reference to an array object, and expect a method to modify the original reference to point to another array object.
You can, of course:
Modify elements of the referred array object (ala java.util.Arrays.sort)
Pass a reference to an object with a settable field (e.g. Throwable has a setStackTrace)
return the new reference instead (ala java.util.Arrays.copyOf)
Well, you can explicitly pass an object that contains a reference. java.util.concurrent.atomic.AtomicReference is ready out of the box, although it does come with volatile semantics that you probably don't want. Some people use single element arrays to returns values from anonymous inner classes (although that doesn't seem a great idea to me).
This method reverses the Array's elements in place. The caller sees the changes. (In Java everything is passed by value, including object references.)
public static void reverse(Object[] arr) {
for ( int i = 0, j = arr.length - 1; i < j; i++, j-- ) {
Object temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
In Java Object reference is passed by value.
So if you looking for something like
function referenceCheck()
{
int[] array = new int[]{10, 20, 30};
reassignArray(&array);
//Now array should contain 1,2,3,4,5
}
function reassignArray(int **array)
{
int *array = new int[] { 1, 2, 3, 4, 5};
}
Then its not possible in Java by any direct means.
If we need to change only the values stored in an array, then we can do it since object reference is passed by value.
You want to pass a reference to the array reference. In that case you just have to either create a class to hold the reference and pass a reference to that class or just pass a 1-element array of the type being passed. Then you'd be passing either an object holding the array or an array whose only element contains the array you want to operate on.

Categories

Resources