Making a variable unchangeable once stored - java

EDIT-
Sorry I may have been unclear in what im asking, the code works in finding the maximum. But once its stored how would I set the variable so If I wanted to change it in the future I can't

First: Declare your final variable without an initial value.
Second: Use a temporary variable to compute the unique value.
Last: Load the temporary value into your final variable.
If it is an instance variable, you'll have to do this computation into every constructor.
Update
class MyClass
{
private final int patientID;
public MyClass()
{
int temp = IDCount;
for (int i=0; PatientInfo.contains(temp) && i < 9999999;i++){
temp++;
}
this.patientID=temp;
}
}

As you initialise the value to zero you check if it is zero and if so it can be updated.
if (patientId == 0) patientId = IDCount +1;
Of course to make this more robust, the patientId should be a private field in another class and the setting should be done in a setter with the above logic.
On a further note, if you are simply want to get use the maximum value, consider using Math.max

You can create somewhere (probably in the PatientInfo class) a static field representing the current maximum PatientID.
Then just assign that number+1 to the newly created Patient and change the maximum.

The thing you want to seems to be pointless. I think you might just want to implement unique constraint on the specified attribute. But if you really want an "once mutable int", you got it:
class CustomInt {
private Integer val;
public void setVal(int val) throws Exception{
if(val != null)
throw new Exception("cannot reassign");
this.val = val;
}
}
But as I marked, it is pointless.

Related

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(); );

Compute number of times instance variable is increased

I'm setting an instance variable to a unique value,
i.eprivate int registrationCourse = 2015000; in an object class.
I want to increase this course number by 1 each time it is called from a main method so it becomes 2015001, 2015002, etc.
I think to do this, I have to create a class variable and initialize it to 0, simply because it is not bound to a class. (Please correct me if I'm wrong)
i.e private static int numCourses = 0;
Then I have to make a constructor, and initialize the other instance variables, and increment the registration number in the following fashion:
numCourses = registrationCourse;
numCourses++;
However, I am super new to dealing with constructors, so I do not understand why I don't have to make a whileloop to do this. My other question would be when I try to return the registrationCourse number, for both cases, it obviously only returns the last incremented value, and I want to return a different valued, increased by one for each object. Any explanations??
Your static value will be shared accross all instances of the class instances. If you like to maintain the actual number that is applicable during the instance-construction, you would need to copy it to a non-static (instance-bound) variable.
For example:
class c{
private int registrationCourse = 2015000;
private int incrementalValue = 0;
private static int nextIncrementalValue = 0;
public c(){
nextIncrementalValue +=1; //increase static, shared value.
this.incrementalValue = nextIncrementalValue; // set CURRENT value for later reference.
}
}
If you now would construct 3 instances of c, each of them would have the same value for nextIncrementalValue (= 3) because they all share the same static variable, but any instance would have it's own incrementalValue (= {1,2,3})
For your question about constructors, you don't need a while loop because your application is only concerned of counting how many objects are created. And for each object, the constructor gets invoked, therefore you only need the increment code in the constructor. You would probably need your while loop in your main() code if you decide how many objects you need to instantiate:
int i = 0;
while(i<10) {
Course course = new Course(); // assuming your class is named Course
}
This will increment the counter 10 times.
For your second question on returning the value per object created, you would need an "instance" variable for this. So create another non-static variable and save the numCourses value in it:
static int totalCourses = 2015000;
int courseNumber = 0;
public Course() {
totalCourses++;
courseNumber = totalCourses;
}
So, what happens here is that the totalCourses just keep on incrementing every new object that you have. then each course number is saved and different per object.
Hope this helps.

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);
}
}

Casting string as a integer member, possible?

Ok my problem isnt really a serious one, im just trying to find a clever way of access/modification of class member variables. Here is the code:
public class Storage{
private int cookies= 0;
private int rolls= 0;
private int candies= 0;
private int lolipops= 0;
private int iceCreams= 0;
public void addCookies(int howMuch){ //this is the dirty way of creating method for
this.cookies = cookies+howMuch; //every member variable
}
public void addValue(String stat, int howMuch){ //i would like to do it only
//by passing the name
//of variable and then cast it as integer
//so that it would relate to my class members
int value = this.(Integer.parseInt(stat)); // <- YES i know its ridiculous
//im just trying to explain what is my aim
value = value + howMuch;
this.(Integer.parseInt(stat)) = value;
}
}
Generally i would like to access a field by passing its name to a method, read value of that member, add to it some value, and then store it. Yes i know that it easily can be done with separate methods, or even with one by using some arraylist and comparisons of member names with parameter passed to method. But i would like to do it "fast" without redundant code writing.
Now i have like 5 members, but what about 15000? My aim is to simplify the whole processing and code writing. So generally is it possible to do such redundant code writing bypass? Since i know that i will always pass appropriate name to method... Unless the rule of thumb is to create method for each variable?
Normally you would use a collection like a Map.
public class Storage{
private final Map<String, Integer> inventory = ...
public void addCount(String key, int count) {
Integer i = inventory.get(key);
if (i == null) i = 0;
inventory.put(key, i + count);
}
I guess that by using reflection you can iterate through the fields/methods of your object and do your computation.
For one specific field:
Field member = myObject.getClass().getField(fieldName);
// If you know the class: Field member = MyClass.class.getField(fieldName);
System.out.println(member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
If you want to something for all the public members:
for(Field member: myObject.getClass().getFields())
// Or you can do: for(Field member: myClass.class.getFields())
{
member.getInt(myObject)); // Get the value
member.setInt(myObject, 4); // Set the value
}
Basically, what you do is that you find the Field object that represents the members of you object, then you can manipulate it.
Most IDEs will generate setters and getters for you. This will do what you want with no bother or effort. If this is insufficient, write a method which uses reflection to set the values.
If you have a class with 15000 members, and by this I assume you mean variables private to a class, then you have other issues to resolve.

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