Setters and getters for arrays - java

I am new to Java and I need some clarification how to approach an issue.
I have a class Epicycle, defined below:
public class Ts_epicycle {
private double epoch;
private double[] tle = new double[10];
}
In another class, Refine I am calling a method that requires the tle array:
// create an instance of Epicycle
Epicycle e = new Epicycle();
methodExample(keps1, keps2, e.tle);
In methodExample, I would be setting the array values for tle
1) What is best way for creating getters/setters for the tle array? (and for the other variable too).
2) In the methodExample, I need to pass in the argument for the whole tle array rather than any particular index of it. How would I go about this.
Apologies if i'm not making it clear.

In fact an interesting question:
In order that altering entries in the gotten array does not alter the original object,
you would need to return a copy of the array. Not so nice.
public class TsEpicycle {
private double epoch;
private double[] tle = new double[10];
public double[] getTLE() {
return Arrays.copyOf(tle, tle.length);
}
}
Alternatively you could use the List class instead of an array:
public class TsEpicycle {
private double epoch;
private List<Double> tle = new ArrayList<>();
public List<Double> getTLE() {
return Collections.unmodifiableList(tle);
}
}
This does not make a copy, but simple disallows at run-time to alter the list.
Here the inefficiency is in the Double objects wrapping doubles.
The best might be to use the new Stream class: for iterating through the doubles:
public class TsEpicycle {
private double epoch;
private double[] tle = new double[10];
public DoubleStream getTLE() {
return Stream.of(tle);
}
}

As a general best practice every field in a class that you need to access from another class should be provided with a getter and (if the object is intended as mutable) a setter.
As well explained by Joop Eggen in his answer is usually a good practice to return a copy or a proxy (for example a List/Collection referencing the array), in order to preserve the state of the original array.

If you want to only allow users to edit the array one at a time, then you can add the synchronized keyword to the method signature. Accessing an array is already thread safe so you don't need anything there
For example:
double getTle(int index) {
return tle[index]
}
synchronized void setTle(int index, double value) {
tle[index] = value;
}
This only allows the method to be called once at a time

your array is an object like any other object in java .
// to declare and initialize your array
private int[] st = new int[10];
//getter and setter
public int[] getSt() {
return st;
}
public void setSt(int[] st) {
this.st = st;
}
//for the last method u can use
public void method(int value)
{
for(int i = 0 ; i<st.lenght ; i++){
st[i] += value; // for exemple
}

Related

Error in Creating Java array with Multiple Data Types

Can someone please explain why it doesn't work? The error is at obj[0][0]=1;. It says that GPA can't be converted to int, same thing for String variable assignment s.
public class GPA {
public String s;
public int n;
public GPA[][] a;
//constructor
public GPA(GPA[][] a){}
public static void main(String[] args) {
GPA[][] obj=new GPA[2][2];
obj[0][0]=1; //error here
}
}
obj is an Array of GPA objects.
obj[0] = 1 means you are assigning the first element of that array to an intvalue. It should be an object of type GPA.
You can do it like
obj[0] = new GPA("John Doe", 6);
I would also recommend using Java convention, by making variables private and set() them by public methods like setter()s.
The question is changed which makes the answer irrelevant.
It won't work and gives you compile time error because GPA is class type and you are trying to assigning int value to it.
You have two options.
Option 1:
GPA[] obj = new GPA[4];
obj[0] = new GPA();
obj[0].n = 1;
Option 2:
You can make members of GPA private and use setters to set the value. Below is example.
public class GPA {
private String s;
private int n;
private GPA[] a;
public GPA() {}
public GPA(GPA[] a) {}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public GPA[] getA() {
return a;
}
public void setA(GPA[] a) {
this.a = a;
}
}
and then set using setter.
obj[0].setN(1);
It's not good programming practice to make your members public. It is always advised to use setters.
What you're actualy doing is trying to assign int and/or string to variable that is expecting object of GPA class.
Didn't you want to do
obj[0].n=1;
obj[0].s="text;"
For array of object you always have to create on object at that position first. otherwise you alway get a NullPointerException.
So what you need goes something like this
GPA[][] obj = new GPA[2][2];
obj[0][0] = new GPA();
obj[0][0].s="text";
obj[0][0].n=1;
...
and so on for every position there is.
Java Arrays are homogeneous(Javascript arrays are heterogeneous). That means you can only store the type of elements which you used while creating an Array.
ex: `int intArray[];` //We can store only int type elements(it also accepts Integer etc.. types but java converts to int then store it)
Now, apply the same rule to public GPA[] a; here a is an array of type GPA. So it accept only GPA type object.
That mean, you can store values like as below
a[0] = new GPA("nameHere", 6);
If I want to store either a string or an int, one at a time( I have
to make table of Student Name vs GPA) ,how do I do it?
One solution to this requirement is, assign a variable using constructor or setter method.
GPA[] obj = new GPA[2];
obj[0] = new GPA("first", 6); // here you need to create a new constructor
or
obj[1] = new GPA(); // Here default constructor will work and you need to have setter methods
obj[1].setName("second");
Hope this help...

How to set up an array with related items

I am trying to make a program that will allow me to manipulate multi-variable polynomials. I want to be able to deal with expressions that have more than one variable, and each with its own exponent. For example, one example of a polynomial object will contain information from 5x^2*y^3.
I want to store this polynomial's information in instance variables: an int for the coefficient, a String[] for the variables, and an int[] for the exponents for each variable.
How would I go about linking the two arrays to relate each variable to it's own exponent? I do not want to just have the variable and it's exponent in the same index of different arrays. I would like to know how to have a more guaranteed way that the data will be properly handled.
Use a single array with a new class like the following
public class Element {
private String variable;
private int coefficient;
private int exponent;
...
}
Then you can create an array like the following:
public Element[] elements;
Please note that you have never talk about the operators... probably you have to add something more to that structure to know the operator between elements.
First create a POJO class to store polynomial variables in the fields coefficient, variable, exponent.
Then call them from another class;
Here is the POJO class, I call it Element;
public class Element {
private double coefficient;
private int exponent;
private String variable;
public Element(double coefficient, String variable, int exponent ) {
this.coefficient = coefficient;
this.variable = variable;
this.exponent = exponent;
}
public double getCoefficient() {
return coefficient;
}
public void setCoefficient(double coefficient) {
this.coefficient = coefficient;
}
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
public int getExponent() {
return exponent;
}
public void setExponent(int exponent) {
this.exponent = exponent;
}
}
And the Test Code is as follows;
public class TestPolynomials {
public static void main(String[] args) {
Element[] polynomialList = { new Element(5,"x",2), new Element(1,"y",3), new Element(6,"1",0) };
printPolynomials(polynomialList);
}
public static void printPolynomials( Element[] pList ) {
for( int i = 0; i < pList.length; i++ ) {
System.out.printf("%2.1f*%s*%d, ", pList[i].getCoefficient(), pList[i].getVariable(), pList[i].getExponent() );
}
}
}
The output is as follows;
5.0*x*2
1.0*y*3
6.0*1*0
Depending on the implementation of your project, the need to create a solid connection between the two might be irrelevant. I will provide an example, because there is an easy way to reference both arrays and get the matching data.
int[] coefficients = ...
String[] exponents = ...
And for referencing, lets say you want the second polynomial... All you need to do is reference the same place in both arrays to get the matching value. Just be sure to update the arrays in tandum, so they do not fall out of sync. I might recommend a specific method for updating them.
//Do some action
coefficients[1].action
exponents[1].action
Why not create a Polynomial class:
Public class Polynomial {
int coefficient;
String variables [];
int exponents [];
public Polynomial (int coeff, String [] var, int [] expo) {...}
then just have an array of polynomial objects..
Polynomial polys [] = new Polynomial[200];
then all of your data is kept in the necessary object and easily access or maintained. if you need a dynamics storage solution use ArrayList instead.

java arrays and creating them

I'm currently in programming in java and I cannot for the life of me understand what is going on here. If any of you could point me in the right direction that would be wonderful.
These are the directions:
Make an instance variable for an integer array.
The ArrayLab constructor will take an integer parameter that will be the number of elements in the array. Create the array inside your constructor. DO NOT save the int parameter as an instance variable.
And this is what I have for code. It obviously doesn't work right, but I have no idea where to go from here.
private int[] integerArray;
public ArrayLab(int inParameter){
integerArray = integerArray[inParameter];
}
Keyword new is used to create Object.
You can doing something like...
public class ArrayLab {
private int[] integerArray;
public ArrayLab(int inParameter) {
this.integerArray = new int[inParameter]; //Creates arrays of integer of length inParameter.
}
}
You are only needed to add new key word when you created an array.
private int[] integerArray;
public ArrayLab(int inParameter){
integerArray = new int[inParameter];
}

Accessing arrays with methods

Hi guys i'm just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method?
The design look like this:
public class Arrays{
int arraysize = 2;
public void initializeArray(){
float array[] = new float[arraySize]; // Declare array
}
public void accessArray(){
// I want to access the array from this method.
}
}
Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html
You can declare the array at class level then it is accessible in all methods.
public class Arrays {
int arraysize = 2;
private float[] array = null;
public void initializeArray() {
array = new float[arraySize]; // Declare array
}
public void accessArray() {
// access array here.
}
}
Or You can pass the variables in method.
public class Arrays {
int arraysize = 2;
public void initializeArray() {
float[] array = new float[arraySize]; // Declare array
accessArray(array);
}
public void accessArray(float[] array) {
// access array here.
}
}
Given the amount of information, I have from question, approach 1 seems better than 2.
You need to move your declaration to make it a member, otherwise it will go out of scope once the initializeArray call ends. Then you can access the array from both methods. Try this:
public class Arrays{
float[] array;
int arraysize = 2;
public void initializeArray(){
array = new float[arraySize]; // Declare array
}
public void accessArray(){
array[0] = 1.0f;
}
}
This is done thusly
public class myClass{
int arraysize = 2;
float[] myArray; // Declare array
public myClass(){
myArray = new float[arraySize]; // initialize array
}
public float[] accessArray(){
return myArray;
}
}
The array declaration must not be done inside the class methods.
Variable declaration done inside a method limits it's scope of a variable to the method. (i.e you can't use it anywhere else).
The array is then instantiated in a constructor.
A constructor is a special function that is run when a class is instantiated.
Constructor are used to instantiated a class's variables
Constructors have the same name as their class and must not specify a return type (so no public int or public void just public)
Next you need to change the return type of the accessArray method. A return type of void states that the method isn't going to return anything. Change it to float[]
Then your accessArray method need only return the array variable.
EDIT: The
"return myArray;"
line of code gives a reference to the array to what ever called the function (Not a copy of the array, the actual array, a quick of Java is that it always does this except when returning primitive data types where it returns a copy)
If you want accessArray() to set floats in the array instead of returning the array it should be implmented like this.
public void accessArray(int index, float value){
myArray[index] = value;
}
There a two options:
You declare that array as instance variable
public class Arrays {
private int arraySize = 2;
private float array[];// Declare array
public void initializeArray() {
array = new float[arraySize];
}
public void accessArray() {
// I want to access the array from this method.
float first = array[0];
}
}
You pass the array as parameter to the method (resp. the initializeArray method should return an array)
public class Arrays {
public static void main(String[] args) {
int arraySize = 2;
float[] array = initializeArray(arraySize);
accessArray(array);
}
public static float[] initializeArray(int size) {
return new float[size];
}
public static void accessArray(float[] floats) {
// I want to access the array from this method.
float first = floats[0];
}
}

how to order set of objects based on array of integers

I have a class called Variable
Class Variable{ private String name; private int[] domain; //...etc}
which represents variable in specific structure (constraint satisfaction problem).
I have instantiated set of variables in ArrayList< Variable > and filled up an array of integers.
ArrayList<Variable> vars=new ArrayList<Variable>();
Variable a=new Variable("A",new int[]{1,2});
vars.add(a);
// Define all variables;
int[] cons=new int[vars.size()];
for(int i=0;i<cons.length;i++)
cons[i]=number_of_constraints(vars.get(i));
// cons contains number of involved constraints for each variable
Now I need to sort them descending based on the number of constraints.
In other words: Given list of Objects [(A,{1,2}) , (B,{3,4}) , (C,{5,6}) ] and an array of integers cons={1,2,0} how to sort the list of objects descending based on the array of integers?
Use a sorted collection like a TreeSet
class Variable {
private String name;
private int[] domain;
};
final Set<Variable> variables = new TreeSet<Variable>( new Comparator<Variable>() {
public int compare(Variable o1, Variable o2) {
//Do comparison here
//return -1 if o1 is less than o2
//1 if o1 is greater than o2
//0 if they are the same
}
});
Now you have a sorted Set of your Variables. This is guaranteed to always be sorted.
If you would like to keep Class Variable intact, the following code will sort the given vars outside:
Collections.sort(vars, new Comparator<Variable>() {
public int compare(Variable var1, Variable var2) {
return var2.number_of_constraints() - var1.number_of_constraints();
}});
If you can change Class Variable, let it implement interface Comparable:
class Variable implements Comparable<Variable> {
//...
public int compareTo(Variable other) {
return this.number_of_constraints() -
other.number_of_constraints();
}
}
Then you can sort vars by:
Collections.sort(vars);
As far as a Variable contains numOfConstraints, according to your code, you can make your Variable class implement Comparable interface, like
public class Variuable implements Comparable<Variable> {
private int numOfConstraints;
public int compareTo(Variable other){
if(this == other) { return 0; }
return (numOfConstraints == other.numOfConstraint) ? 0 : ((numOfConstraints > other.numOfConstraint) ? 1 : -1);
}
}
And then use the utility method java.util.Collections.sort(vars);, that's it.
Your Variable class should implement the Comparable interface,
When it does you should implement the compareTo method.
After that you can sort it by calling the Collection.sort method.
If you want to sort by a permutation if your indexes that's just a matter of creating a new ArrayList and mapping each index to the new index (using a for loop)
Here is such a (generic) method
public static <T> ArrayList<T> permutate(ArrayList<T> origin,int[] permutation){
ArrayList<T> result = new ArrayList<T>(permutation.length);
for(int j=0;j<permutation.length;j++){
result.add(null);
}
for(int i=0;i<permutation.length;i++){
result.set(i, origin.get(permutation[i]));
}
return result;
}
You can do myArrayList= permutate(myArrayList, new int{1,2,3});
Here is example usage in a more basic use case (integers):
public static void main(String... args){
ArrayList<Integer> origin = new ArrayList<>(4);
origin.add(1);
origin.add(2);
origin.add(3);
origin.add(4);
int[] per = new int[]{2,1,3,0};
origin = permutate(origin,per);
System.out.println(Arrays.toString(origin.toArray())); //prints [3,2,4,1], your permutation
}

Categories