Handling Static Collections in Java - java

say I have a class A which is as follows
public class A {
protected static float[] floatArray = null;
protected static Map<Integer, float[]> history = new HashMap<Integer,float[]>();
protected static Integer historyCount = 0;
public void runEverySecond(Populator objPopulator) {
floatArray = objPopulator.getValues();
history.put(historyCount, floatArray);
historyCount++;
}
}
and Class B looks as follows
public class B {
private A objA;
protected final static Populator objPopulator = new Populator();
public void run(Integer numOfTime) {
for(int i = 0; i < numOfTime; i++)
objA.runEverySecond(objPopulator);
}
}
and Class Populator looks as follows
public class Populator {
protected float[] randomValues = new float[2];
public float[] getValues() {
randomValues[0] = //some new random float value generated for every call
randomValues[1] = //some new random float value generated for every call
return randomValues;
}
}
and class containing main looks as follows
public class MainClass {
public static void main() {
final B objB = new B();
objB.run(10);
}
}
Here is the problem I am facing, the Map history contains the same value for every entry in the map. I want the Map history to store all the values generated by objPopulator.getValues() method. How do I do it?
Some help would be really appreciable.
Thanks in Advance :)
The Actual code (with irrelevant code removed ) represented by class A
public class MySuperAgent implements Agent {
protected static float[] marioFloatPos = null;
protected static Map<Integer, float[]> levelRecord = new HashMap<Integer, float[]>();
protected static Integer mapCount = 0;
/* protected static int testCount = 0;
protected static float[] testx = new float[2];
protected static float[] testy = new float[2];*/
#Override
public void integrateObservation(Environment environment) {
marioFloatPos = environment.getMarioFloatPos();
levelRecord.put(mapCount, marioFloatPos);
mapCount++;
/*if(testCount < 2){
testx[testCount] = marioFloatPos[0];
testy[testCount] = marioFloatPos[1];
testCount++;
} else {
testCount = 0;
}*/
}
}
class C represent environment object
integrateObservation method is called from class similar to class B
if I use the code within the comment block then I am able to record only 2 past values of x and y of Mario. I need a way to store all the values of x and y of Mario :)

Every entry in your Map has a reference to the same static field floatArray as its value.
Instead of having floatArray as a static member variable in A consider:
public void runEverySecond(Populator objPopulator) {
float[] floatArray = objPopulator.getValues();
history.put(historyCount, floatArray);
historyCount++;
}
EDIT Also I don't know how your code for class A would compile as it is. Shouldn't runEverySecond take a Populator parameter instead of Object? See revised snippet above.

There's only one floatArray and you keep reassigning it.
This code was almost impossible to follow in a reasonable way--what a mess.

Related

List of inheriting objects java

I created a little example. Imagine I have two classes:
public class Neuron {
ArrayList<Neuron> neighbours = new ArrayList<>();
int value = 1;
public Neuron() {
}
public void connect(ArrayList<Neuron> directNeighbours) {
for (Neuron node : directNeighbours) {
this.neighbours.add(node);
}
}
}
and a class that inherits from Neuron:
public class SpecialNeuron extends Neuron {
int value = 2;
public SpecialNeuron() {
}
}
In my case, I want the inheritance in order to avoid a lot of "if object is special do something" stuff. However, when I am calling:
public static void main(String[] args) {
ArrayList<Neuron> neurons = new ArrayList<>();
Neuron a = new Neuron();
Neuron b = new Neuron();
Neuron c = new Neuron();
neurons.add(b);
neurons.add(c);
a.connect(neurons);
ArrayList<SpecialNeuron> special = new ArrayList<>();
SpecialNeuron d = new SpecialNeuron();
SpecialNeuron e = new SpecialNeuron();
special.add(d);
special.add(e);
a.connect(special); //Error
}
it is not possible to use a List(SpecialNeuron) for a List(Neuron) parameter. What is wrong with this call, and is there a proper way to solve that issue?
Furthermore, I could do
ArrayList<Neuron> special = new ArrayList<>();
Neuron d = new SpecialNeuron();
Neuron e = new SpecialNeuron();
special.add(d);
special.add(e);
a.connect(special); //works fine
Which works, but denies any usage of functions from the SpecialNeuron class.
You can make use of WildCards in Generic <? extends T>.You can read more about it here.
Change your method param to this.
public void connect(ArrayList<? extends Neuron> directNeighbours) {
for (Neuron node : directNeighbours) {
this.neighbours.add(node);
}
}
First of all, you're extending Neuron class, but you're not really using inheritance. You should make value variable protected and set its value in constructor.
public class Neuron {
protected int value;
public Neuron() {
this.value = 1;
}
}
public class SpecialNeuron extends Neuron {
public SpecialNeuron() {
this.value = 2;
}
}
Now, your problem is on the line 17 - ArrayList<SpecialNeuron> special = new ArrayList<>(); - you have List of SpecialNeuron objects, that are children of Neuron class, so Java knows it contains only objects of class SpecialNeuron
In your connect() function, you accept only Neuron class objects, so in order to make it work, you have to change your special list to:
ArrayList<Neuron> special = new ArrayList<>();
In this List, you can add Neuron and SpecialNeuron objects and use it as a List of Neuron objects.

Using array of objects amd methods from one class in another class errors - JAVA

I'm fairly new to Java and I'm struggling to understand a few concepts. What I am trying to achieve is constructing a Magazine in Magazine class, which requires an array of objects from the Supplement class in its constructor. I've created a method inside Supplement which fills up an array of objects of supplements, and I'm trying to call this method inside Magazine to fill up another supplement object I have created in there. Then, I am trying to pass that array of objects to the Magazine constructor so that one magazine can have this array of 4 supplements. Make sense?
The problem I'm facing firstly, is that my method fillArray is not recognized in Magazine from class Supplement. All my classes are under the same source package, so what's the problem here? Some feedback on where I may be going wrong with my logic some guidance in the right direction would be helpful as I have to apply this logic for some other associated classes as well and I'm not quite sure how to go about it.
Another question I have, is that upon doing some research I see that some people use public static void main(String args[]) in their classes for some operations. What is the purpose of this, as I thought it was only used inside the client program, and if it is used in classes what would be the use of the client program?
Magazine.java:
public class Magazine {
private String magazinename;
private int WeeklyCost;
private Supplement[] supplement;
public static void main(String args[]){
Supplement[] supplements = new Supplement[3];
supplements.fillArray();
Magazine magazineobj = new Magazine("The Wheels Special", 35, supplements);
};
public void SetMagazineName(String magazinename1){
magazinename = magazinename1;
};
public void SetWeeklyCost(int WeeklyCost1){
WeeklyCost = WeeklyCost1;
};
public String GetMagazineName(){
return magazinename;
};
public int GetWeeklyCost() {
return WeeklyCost;
};
public void SetMagazine(String magazinename1, int WeeklyCost1, Supplement[] supplements1){
magazinename = magazinename1;
WeeklyCost = WeeklyCost1;
supplement = supplements1;
};
public Magazine(String magazinename1, int WeeklyCost1, Supplement[] supplements1){
SetMagazine(magazinename1,WeeklyCost1,supplements1);
};
}
Supplement.java:
public class Supplement {
private String supplementname;
private int WeeklySupCost;
Supplement[] supplements = new Supplement[3];
public void fillArray(){
supplements[0] = new Supplement("Sports Illustrated Special", 4);
supplements[1] = new Supplement("Health and Nutrition", 2);
supplements[2] = new Supplement("Lifestyled", 5);
supplements[3] = new Supplement("Gamer's Update", 3);
}
public void SetSupplementName(String supplementname1){
supplementname = supplementname1;
};
public void WeeklySupCost(int WeeklySupCost1){
WeeklySupCost = WeeklySupCost1;
};
public String GetSupplementName(){
return supplementname;
};
public int GetWeeklyCost(){
return WeeklySupCost;
};
public void SetSupplement(String supplementname1, int WeeklySupCost1){
supplementname = supplementname1;
};
public Supplement(String supplementname1, int WeeklySupCost1){
SetSupplement(supplementname1, WeeklySupCost1);
}
}
Your problem is that you are attempting to call the Supplement instance method fillArray() on a Supplement[], not a Supplement.
You need to call the fillArray() method on each element of the array (rather than on the array).
Change:
supplements.fillArray();
to:
for (Supplement supplement : supplements) {
supplement.fillArray();
}
Change fillArray as below,
public Supplement[] fillArray(){
Supplement[] supplements = new Supplement[3];
supplements[0] = new Supplement("Sports Illustrated Special", 4);
supplements[1] = new Supplement("Health and Nutrition", 2);
supplements[2] = new Supplement("Lifestyled", 5);
supplements[3] = new Supplement("Gamer's Update", 3);
return supplements;
}
And then create Supplement object and call fillArray ,
public static void main(String args[]){
Supplement supplement = new Supplement();
Supplement[] supplements = supplement.fillArray();
Magazine magazineobj = new Magazine("The Wheels Special", 35, supplements);
};
About the main method, check here

Java array list returning 0 value

I have created a class like this, which contains a bunch of arraylist as you can see. I've been setting the array with the methods add.. and then retrieving it with get.., when i tried to System.out.println numberofcitizen for example it is returning 0. Note that i have instantiated the class in another class to set the values.
public int numberOfCitizen;
private final ArrayList<Integer> citizenid = new ArrayList<>();
private final ArrayList<String> citizenName = new ArrayList<>();
private final ArrayList<Integer> citizenWaste = new ArrayList<>();
private final ArrayList<Float> longitude = new ArrayList<>();
private final ArrayList<Float> latitude = new ArrayList<>();
private final ArrayList<String> address = new ArrayList<>();
public void working() {
System.out.println("executing fine");
}
public void setnoOfcit(int number) {
this.numberOfCitizen = number;
}
public int getnumber() {
return this.numberOfCitizen;
}
public void addCitizenId(int citizen) {
citizenid.add(citizen);
}
public int getCitizenid(int i) {
int citId = citizenid.get(i);
return citId;
}
public void addCitizenName(String citizenname) {
citizenName.add(citizenname);
}
public String getCitizenName(int i) {
return citizenName.get(i);
}
public void addCitizenWaste(int waste) {
citizenWaste.add(waste);
}
public int getCitizenWaste(int i) {
return citizenWaste.get(i);
}
public void addLatitude(float lat) {
latitude.add(lat);
}
public float getLat(int i) {
return latitude.get(i);
}
public void addlng(float lng) {
longitude.add(lng);
}
public float getlng(int i) {
return longitude.get(i);
}
com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder vrpBuilder = com.graphhopper.jsprit.core.problem.VehicleRoutingProblem.Builder.newInstance();
public void runVPRSolver() {
System.out.println(numberOfCitizen);
System.out.println(getCitizenName(0));
//create a loop to fill parameters
Probable source of problem :
numberOfCitizen is a member attribute that you seem to never change. If you want it to represent the number of elements in your lists, either use citizenName.size() or increment the value of numberOfCitizen in one of the add methods.
Design flaw :
Your design takes for granted that your other class always use that one properly. Anytime you or someone uses that class, he must make sure that he add every single element manually. This adds code that could be grouped inside your class, which would be cleaner and easier to maintain.
So instead of several add method like this :
addCitizenid();
addCitizenName();
addCitizenWaste();
addLongitude();
addLatitude();
addAddress();
Design an other Citizen class which will contain those elements, and use a single list of instances of that class. That way you can use only one method :
private List<Citizen> citizenList = new ArrayList<>();
public void addCitizen(Citizen c) {
/*Add element in your list*/
citizenList.add(c);
}
This programming methodology is called "Encapsulation" which you can read about here
You need to increment numberOfCitizen in your add methods. For example:
public void addCitizenId(int citizen){
citizenid.add(citizen);
numberOfCitizen++;
}
I would also suggest encapsulating your variables into Objects, so create a citizen class:
public class Citizen {
private Integer id;
private Integer name;
private Integer waste;
}
And change your variable to an ArrayList of objects:
ArrayList<Citizen> citizens;

I need a way to randomize outcomes passing and holding classes

I'm trying to add let's say 5 classes that they all extend a General class and implements an init() method in a different way.
What I need is a way to store those classes while passing a number of chances for that Class to "happen"
For this I created a Class holder:
public class ClassHolder {
private Class<? extends GeneralOutcome> holdClass;
private int chances;
public ClassHolder(Class<? extends GeneralOutcome> holdClass, int chances) {
super();
this.holdClass = holdClass;
this.chances = chances;
}
public Class<? extends GeneralOutcome> getHoldClass() {
return holdClass;
}
public void setHoldClass(Class<? extends GeneralOutcome> holdClass) {
this.holdClass = holdClass;
}
public int getChances() {
return chances;
}
public void setChances(int chances) {
this.chances = chances;
}
}
Also a GeneralOutcome class that the ones that will be added to a list will extend:
public class GeneralOutcome {
public void init(String text, int times) {
}
}
And the way I'm adding them to a list:
public class Randomizer {
private static List<ClassHolder> myList = new ArrayList<ClassHolder>();
private static ClassHolder outcome01 = new ClassHolder(Outcome01.class, 10);
private static ClassHolder outcome02 = new ClassHolder(Outcome02.class, 10);
private static ClassHolder outcome03 = new ClassHolder(Outcome03.class, 10);
private static ClassHolder outcome04 = new ClassHolder(Outcome04.class, 10);
private static ClassHolder outcome05 = new ClassHolder(Outcome05.class, 10);
public static void main(String[] args) {
for(int i = 0; i < outcome01.getChances(); i++) {
myList.add(outcome01);
}
for(int i = 0; i < outcome02.getChances(); i++) {
myList.add(outcome02);
}
for(int i = 0; i < outcome03.getChances(); i++) {
myList.add(outcome03);
}
for(int i = 0; i < outcome04.getChances(); i++) {
myList.add(outcome04);
}
for(int i = 0; i < outcome05.getChances(); i++) {
myList.add(outcome05);
}
System.out.println(myList.size());
int rand = (int) (Math.random() * myList.size());
System.out.println(rand);
ClassHolder theHoldClass = myList.get(rand);
System.out.println(theHoldClass.getHoldClass());
Class<? extends GeneralOutcome> theOutcome = theHoldClass.getHoldClass();
theOutcome.init();
}
}
The problem is that I'm not able (Don't know how really) cast back to GeneralOutcome to I can access the .init() method.
I get The method init() is undefined for the type Class<capture#3-of ? extends GeneralOutcome>
I know this isn't the best way to do this. So I'm open to both, a fix for this and also what would be a better way to achieve something like this.
What you are trying to do here doesn't work for some reasons.
First of all, your init method isn't static. So that call
Class<? extends GeneralOutcome> theOutcome = theHoldClass.getHoldClass();
theOutcome.init();
leads directly to a compile-time error.
But then, the whole design looks strange. What is the point of holding Class objects in the first place?
Why don't you create an interface
public interface OutcomeFunctionality {
public void foo(String text, int times);
}
to later instantiate objects of whatever class implementing that interface? So that you can finally can deal with lists of such objects (together with those probabilities)?
[ I used the name foo on purpose: alone the strange name "init" makes it very unclear what your code is intended to do! In that sense you should rethink your design, and find better method names to express what those methods will be doing! ]
Long story short: using/holding Class objects doesn't buy you anything in your example code - it only adds complexity. So my advise is: start working there and get rid of that "detour". You might also want to read about the Open/Closed principle - that could give you some guidance how a good OO design looks like that uses abstract classes / subclassing in order to split "behavior" between base and derived classes.

Accessing each member in a class in Java like in struct in C

Im a beginner in Java. I read that structs in C are similar to classes in Java, but I have the following doubt.
I have a class as follows:
public class operations {
public Integer[] stream;
public Integer[] functi;
public String[] name;
public Integer[] funcgroup;
}
I get an input from the user for name and compare it with the name array in the class and if there is a match, I want to return the records for all the other fields corresponding to the name.
For eg. if name corresponds to String[5], then I want to output all the records corresponding to [5]..i.e stream[5], functi[5], functigroup[5].
How can I do this?
EDIT Now my program looks like this:
public class operations extends DefFunctionHandler {
public ArrayList<Integer> stre = null;
public ArrayList<Integer> functii = null;
public ArrayList<String> nmee = null;
public ArrayList<Integer> funcigroup = null;
public ArrayList<Integer> sourcee = null;
public void filter(String x){
DefFunctionHandler defi = new DefFunctionHandler();
functii = defi.getFunc();
stre = defi.getStream();
nmee = defi.getName();
funcigroup = defi.getFuncgroup();
sourcee = defi.getSource();
Map<String, operations> map = new HashMap<String, operations>();
operations operations = new operations(0, 0, x, 0, 0);
map.put(x, operations);
operations op = map.get("flush");
System.out.println(op.toString());
}
And I get a message saying that I have to declare a constructor for operations with parameters(int, int, string,int, int). Can anyone tell me if my Map interface implementation is correct?
You should store your operation objects into a Map
A map works with key/value, you put an id into the map, and you can retrieve the corresponding key.
In your example, use the class Operation :
public class Operation {
public int stream;
public int functi;
public name;
public int funcgroup;
}
and a map like this :
Map<String, Operation> map = new HashMap<String, Operation>();
Operation operation = new Operation(0,0,"name5", 0);
map.put("name5", operation);
You can retrieve your Operation object with :
Operation op = map.get("name5");

Categories

Resources