Java Can I set variable in class depending on the input - java

I would like following effect -> I have object of class FluidArray which will be an array, but depending on the input it will be either int array or String array:
FluidArray XXX = new FluidArray;
XXX.YYY[] might be either String or int
In this case variable YYY of class XXX might be int array or String
Can I somehow declare variable type depending on some choice?
public class FluidArray
{
VarType YYY;
public static void FluidArray(int a)
{
double[] YYY = new double[15];
}
public static void FluidArray(String a)
{
String[] YYY = new String[15];
}
}
Let's say I want to make a sort method.
I input there unsorted array.
I take out sorted array.
The catch is I might want to sort String, double or int array and I don't want to write 3 sorting methods - I thought that my sorting method might work on some defined object and this object will be either String, double int depending on my choice.
I am trying to use Generic type, I got so far sth. like this:
public class test
{
public static void main(String[] args)
{
FluidArray<Integer> arrTest = new FluidArray<>();
arrTest.arr[1]=2;
arrTest.arr[2]=3;
arrTest.arr[3]=4;
}
public static class FluidArray<arrType>
{
public arrType[] arr = (arrType[])new Object[15];
}
}
I don't understand, why I can't get access to the array, compiler ends when inserting first value.

Read up on Generics. Thats what they are supposed to do

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...

Trick the private keyword in Java

I am aware that the idea of the keyword private is to enable encapsulation. However, I got confused when I realized that I can modify an Array after retrieving it with a getter, which surprised me. The same didn't work for the plain integer, although I thought java treats all variables as objects.
The example:
public class PrivContainer {
private int[] myIntArray;
private int myInt;
PrivContainer(){
myIntArray=new int[1];
myIntArray[0]=3;
myInt=22;
}
public int[] getIntArray(){
return myIntArray;
}
public int getInt(){
return myInt;
}
public void printInt(){
System.out.println(myIntArray[0]);
System.out.println(myInt);
}
}
public class Main {
public static void main(String[] args){
PrivContainer pc=new PrivContainer();
int[] r=pc.getIntArray();
int q=pc.getInt();
r[0]=5;
q=33;
pc.printInt();
}
}
The Output of printInt() is 5,22
This means that main method could change the entries of the private array but not of the private int.
Could someone explain this phenomena to me?
An array is a mutable Object. Therefore, if you have a reference to that array, you can modify its contents. You can't do the same with primitive members of a class (such as int) and with references to immutable class instances (such as String and Integer).
Your assignment :
q=33;
Would be similar to :
r = new int [5];
Both of those assignments cause the variables to contain new values, but they don't affect the state of the PrivContainer instance from which the original values of those variables were assigned.
Nothing seems strange here. What happen basically as follow.
public class Main {
public static void main(String[] args){
PrivContainer pc=new PrivContainer(); <-- create new `PrivContiner` object which also initialised the private variables
int[] r=pc.getIntArray(); <-- you get the "object" integer array here and assign r to refer to that object
int q=pc.getInt(); <-- you get the "primitive" integer here and assign q to refer the myInt variable here.
r[0]=5; <-- you assign the first value of the array 5. Note that the object reference is still the same here
q=33; <-- you assign the variable q to 33. Note that, this mean, the variable q refer to another primitive here (which is 33)
pc.printInt(); <-- print the content of the object here.
}
}
When you invoke the printInt function. the output will be 5 and 22 as the new integer (33) is assigned to q and its scope is only within the main function.
While you return an array from a getter you return the reference of that object. Since you have the reference you can change its elements. If you want to avoid this behavior you will have to return the clone of your array in that case you wont be able to change the elements of your array
public class Main {
public static void main(String... args) {
Arr arr = new Arr();
int[] y = arr.getX();
y[1] = 5;
System.out.println(arr.getX()[1]);
}
}
class Arr {
private int[] x = {1, 2, 3};
public int[] getX() {
return x.clone();
}
}
Try this code and remove the clone method, like this
class Arr {
private int[] x = {1, 2, 3};
public int[] getX() {
return x;
}
}
Now execute the main method, you will observe that changing value of y will change the value of array x as well.

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.

Adding numbers to arrays with methods in another class?

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

Varargs, immutable array, and thread-safety

Hi all I have an immutable array implementation which looks like this:
public static final class FixedArray<T> {
private final T[] array;
public final int Length;
#SafeVarargs
public FixedArray(T... args) {
array = args;
Length = args.length;
}
public T Get(int index) {
return array[index];
}
}
public static final class FixedIntArray {
private final int[] array;
public final int Length;
public FixedIntArray(int... args) {
array = args;
Length = args.length;
}
public int Get(int index) {
return array[index];
}
}
public static final class FixedLongArray {
private final long[] array;
public final int Length;
public FixedLongArray(long... args) {
array = args;
Length = args.length;
}
public long Get(int index) {
return array[index];
}
}
Initially I'd thought that it is guaranteed to be thread-safe. But after reading the discussion regarding immutable arrays and the Java Memory Model, I believe alone, I can't be sure.
I've not used a defensive copy, with the contract that the calling code "does the right thing" (and as usual, if it doesn't follow the contract, the behavior is undefined).
The calling method looks like this:
public static void main(String args[]) {
int[] ints = new int[10000];
FixedIntArray fixed_ints = new FixedIntArray(ints);
SendToThreadA(fixed_ints);
SendToThreadB(fixed_ints);
SendToThreadC(fixed_ints);
SendToThreadD(fixed_ints);
//caller (which is this method) does the right thing, ints goes out of scope without anyone trying to modify it.
}
I was wondering is the code above guaranteed to be thread-safe?
As we don't know what happens to the array (and its values) to which you store a reference, I think your classes would be much safer if the constuctors create a copy of the argument array and set the internal final reference to the copied array.
It's OK. You can require caller to "hand-off" the array to you. Caller can clone one if necessary.
Memory write is usually the most expensive thing in a program (sans external IO).
Not everybody is stupid. You only need to be defensive enough to protect your target user base.
Given that you can pass an array to a varargs method, you'd need to make a copy of the constructor input to ensure it can't be modified outside the class. Having done that, as long as you don't assign the final field until after all the values are assigned in the copy array, you should be fine because the assignment to the final field is guaranteed to happen before any read of that field from another thread.
So a constructor would look like:
array = Arrays.copyOf(args, args.length);
Orrrr you could just use a Guava ImmutableList and get a lot more power.
I'm not sure it's meaningful to examine it for thread-safety, because it's missing even a more basic level of safety. Consider this method:
public static void main(final String... args)
{
final int[] arr = new int[] { 3, 3, 3 };
final FixedIntArray threeThrees = new FixedIntArray(arr);
System.out.println(threeThrees.Get(0)); // prints "3"
System.out.println(threeThrees.Get(1)); // prints "3"
System.out.println(threeThrees.Get(2)); // prints "3"
arr[0] = arr[1] = arr[2] = 4;
System.out.println(threeThrees.Get(0)); // prints "4"
System.out.println(threeThrees.Get(1)); // prints "4"
System.out.println(threeThrees.Get(2)); // prints "4"
}
The problem is that, when a method that takes int... (or Object... or long... or anything else), it can receive either an array that's implicitly constructed by the compiler (as would happen if you typed new FixedIntArray(3,3,3)), or an array that's explicitly passed in by the calling code (as I did above). In the latter case, the calling code can continue to modify the array that it passed in!

Categories