How to convert a string variable value into a variable name - java

There are around 10 different types of 2D arrays of varied sizes. eg:
int arr1[][];
float arr2[][];
long arr3[][];
String arr4[][];
Each array needs to be printed at different intervals during the program execution. There is a method defined print2DArray() which takes the 2D array as parameter calculates the number of rows and columns and print the array. But since the arrays are of varied datatypes overriding methods need to be written for each data type.
Can we create a variable as: String arrName;
and pass it to the method print2DArray() and decode the String to obtain the array to be printed.
eg:
if method is called as: print2DArray(arr2);
and method is defined as:
void print2DArray(String arrName){
**Some code to identify which array is reffered by arrName to print**
}

You need to use java reflection api for this purpose .
Code will be somewhat like this.
class CustomClass {
int[][] arr1 = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 8, 7 } };
public static void main(String[] args) {
CustomClass c = new CustomClass();
Field[] f = c.getClass().getDeclaredFields();
for (int i = 0; i < f.length; i++) {
if (f[i].getName().equals("arr1")) {
System.out.println(c.arr1[0][0]); // your own logic
} else if (f[i].getName().equals("arr2")) {
System.out.println(c.arr2[0][0]); // your own logic
} else if (f[i].getName().equals("arr3")) {
System.out.println(c.arr3[0][0]); // your own logic
} else if (f[i].getName().equals("arr4")) {
System.out.println(c.arr4[0][0]); // your own logic
}
}
}
}

I don't think you could do that natively. There's some easy workarounds though, the one i'd choose is to create a Map which contains all of your arrays linked with a key that would be the array name. That way, in your print2DArray function, you'd simply have to iterate your map and find the array that has the correct key (the one you give as a parameter in your function).
Your map would look something like this {"arr1", arr1}, {"arr2", arr2} etc... this would obviously force you to keep track of every newly created array by adding it in your Map (which isn't very costly anyways)

Related

Sorting an object array into another array based on a variable

I have a problem with a program I'm writing for a school assignment.
Essentially, before this piece of code, I already recieve and work with a bunch of information that I store into an array of objects. Now I have to sort this array (after it's sorted, I will have to calculate some things in the order of the PRIORITY variable).
presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.
MyClass[] priorityArray = new MyClass[input.length];
for (int i=0; i<priorityArray.length; i++) {
int maxIndex = 0;
int maxPrivilege = input[i].returnPrivilege();
for (int j=1; j<input.legnth; j++) {
int currentPrivilege = input[j].returnPrivilege();
if (currentPrivilege > maxPrivilege) {
maxPrivilege = currentPrivilege;
maxIndex = j;
}
}
priorityArray[i] = input[maxIndex];
input[maxIndex].setPrivilege(-900000000);
}
the MyClass class if nothing fancy, but of course, contains a proper constructor, getter and setter methods and an integer variable "privilege".
I'm getting an error in my final tests of the program and, seeing as the program returns privileges as "-900000000", it has to have something to do with this part of the code.
It's also not even writing certain MyClass instances from the input array into the priorityArray array.
How can I clead this up? Help.
I'll rewrite my answer totally.
In this line
priorityArray[i] = input[maxIndex];
You are assigning object from one array to another array by reference. It means that there is only one object and you set value to -9000000 in the next line to it. Of course element in priorityArray will have the same changes. To fix it you need to clone your object here.

Return specific value from a 2D array

I'm trying to figure out a way to return the value from a specific position inside a 2D array in JAVA. I've been searching for hours. I might be tired, or using the wrong terms but I can't find anything useful so far...
So for example I have a variable "a" and I want it to receive the value that is contained at a specific array position.
So for example, I want the value contained at the position :
array[1][1]
To be saved into the variable "a". Any way to do this? Btw it's a 9x9 array so it contains 81 different value but I only need 1 specific value out of the array at a time.
Thanks in advance!
You just assign the value from the array as desired:
public class Foo {
public static void main(String[] args) {
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
int a = arr[1][1];
System.out.println(a);
}
}
// outputs : 5
Note that if a value hasn't been put in an array position then it will be in the uninitialized state. For an int this is 0.
int[][] arr = new int[9][9];
// all values in arr will be 0
Depending on the "Object type" you would assign using Object a = array[1][1]; and you can be more specific, as in int a = array[1][1];. GL

Array reference type in a method

I have been given a starting code to work on a project, however I am confused about the following code and cant seem to find any examples online!
public static Entity[][] read(){ ... }
How can I handle this Entity to add new entries to an array, and then how can I return this?
The following constructor is invoked by a different class.
public World() {
aWorld = new Entity[SIZE][SIZE];
int r;
int c;
for (r = 0; r < SIZE; r++) {
for (c = 0; c < SIZE; c++) {
aWorld[r][c] = null;
}
}
aWorld = FileInitialization.read();
}
I feel it would be much simpler if the array was just a parameter or if it were something like:
public static int[][] read(){ ... }
UPDATE:
The goal is to read from a file in the method read() and then assign the an entity to the correct location based on the location in the file. But I am not able to assign since the data types would be incompatible, Required is Entity, but I want to be able to set it to an int, char or String.
To add to an array of objects, you do exactly what you would with an array of primitives (e.g. ints), you just use Entitys. So if you want to add something to aWorld you use
aWorld[r][c] = new Entity(...); //with provided constructor's parameters
// or
aWorld[r][c] = existing_Entity; //for an Entity variable you already have
When you're done adding, you simply return the array aWorld.
If FileInitialization's static read() is going to return Entity[][], that's an entity array by itself. It means that you shouldn't iterate aWorld, rather assign the return value to it directly like
aWorld = FileInitialization.read();
Inside the read(), use that for loop you've made in the constructor and add a new Entity object as noted by Linus
Alright I would like to say thanks to all of you here as I was set on the right direction. But I would like to share my answer which should be simple and hopefully make someones life easier in the future.
To initialize the array of objects just do it as you would initialize any other array, in this case:
Entity[][] reference_name = new Entity[SIZE][SIZE];
To return this value, simply return the reference:
return reference_name;
Now the part where you actually modify an entry into your array.
Lets say you have something like
public static void Entity[][] read() { .. }
you need to create a class file Entity.java (same name as the array type being passed)
In this case it would look something like this:
public class Entity {
private char appearance;
public Entity(char anAppearance) {
appearance = anAppearance;
}
now to give this array an entry do something like this:
reference_name[0][0] = new Entity('X');
alright and in case you are wondering how to display this just add an accesor method to class Entity.
public char getAppearance() {
return(appearance);
}
and to output:
System.out.println(reference_name[0][0].getAppearance(); );

java method to change the value of an array to null

public void setData(double[] d) {
if (d == null) {
data = new double[0];
} else {
data = new double[d.length];
for (int i = 0; i < d.length; i++)
data[i] = d[i];
}
}
this method in my code is used to set the data of an array. I am also required to write a method called reset() that changes a given array to have a null value. Also, we are practicing overloading in this lab. There are four versions of setData() (double, int, float, long). Since a double array is used internally by the Stat class to store the values, do I only have to make one reset() method of type double?(I think I only need one...) Finally, please give me some hints as to going about this reset business because everything I have tried has failed miserably and usually consists of statements such as
"setData(double[] null)" which return errors.
Everything in java is pass by value; even references are passed by value. So by passing an array through a method, you can change the contents of the array, but you cannot change what the array points to. Now, if you are inside a class and happen to pass an instance member that you already have access to by virtue of being in the class, you will be able to set the array to null.
If you always want to be able to change what an array points to, then simply have a function which returns an array (instead of being void), and assign that returned value to the array of interest.
Because java is pass by value, you can't reassign a variable passed as a parameter to a method, and expect to see that change reflected outside.
What you can do, is put the array in some sort of wrapper class like this:
class ArrayReference<T> {
T[] array; // T would be either Double, or Long, or Integer, or whatever
}
and then:
void setData(ArrayReference<Double> myReference) {
myReference.array = null;
}
I'm not sure if I understood your question, but is it that what you want?
public class Stat {
private double[] data;
public void reset() {
data = null;
}
public void setData(double[] d) {
data = (d == null) ? new double[0] : Arrays.copyOf(d, d.length);
}
}

Sorting an array once in a function which is called many times

Is this possible?
I have a function which accepts a user string and then splits into an array of words. I'm going to sort the array and de-duplicate it.
However, it will be used in a function which is called in an iterative step. It actually iterates over a database and checks for each word in the user defines string in each field.
I would like to only sort and de-dup the array once but call the function many for that particular instance of the class. Should I just store the sorted array in a static instance variable?
Thanks for your time
My code is something like this (pseudo-code):
public class searchAssistant{
private float mScores[][];
private Cursor mCursor;
public searchAssistant(Cursor c){
mCursor = c;
}
private float scoreType1(String typeFromCursor, String typeFromUser){
if (typeFromCursor == typeFromUser) {return 1}
else {return 0}
}
//similar method for type scoreType2 but sorting an array
private int[] scoreAll(){
int 1 = 0;
do {
mScores = ScoreType1(mCursor.getString(), smomeString) + scoreType2(...);
itr++;
} while(cursor.moveToNext)
return mScores;
}
}
is this the wrong way to be doing things?
No. Change the signature of the method called multiple times to make it accept the array, and compute the array before calling the method:
Instead of
String s = "...";
while (someCondition) {
someMethodCalledMultipleTimes(s);
}
Use something like this:
String s = "...";
String[] array = computeTheArrayFormTheString(s);
while (someCondition) {
someMethodCalledMultipleTimes(array);
}
Should I just store the sorted array in a static instance variable
"Static instance variable" is an oxymoron.
You almost certainly shouldn't store it in a static variable.
It might make sense to store it in an instance variable. This may have consequences for thread safety (don't know if that's relevant to your situation).
If the iteration is performed by a function defined in the same class, it might make sense to do the sorting inside that outer function and simply pass the sorted array to the inner function every time you call it.
If all of this is happening in the same Thread, you can use a ThreadLocal to save the sort state:
private static final ThreadLocal<Boolean> SORT_STATE = new ThreadLocal<Boolean>(){
protected Boolean initialValue(){return Boolean.FALSE;}
};
public void doSomething(String[] array) {
if(!SORT_STATE.get().booleanValue()){
// then sort the array here
SORT_STATE.set(Boolean.TRUE);
}
// now do everything else
}
You would store it in a non-static instance variable (there is no such thing as static instance variable - these are opposite things).
If your application is not multithreaded you can do the sorting and dedupping the first time and than store the result. (Same if it's multithreaded, but then you need to use locking of some sort).

Categories