For an assignment, I'm having to resize an array within a class, and due to the classes nature, it is easier to just create a new object of the class and then reassign itself?
Let me try and explain with code
public class foo {
// String Array instance
private String[] array;
// Constructor with a String array as a variable to initialize it's instance
public foo(String[] array){
this.array = array;
}
public void reassign() {
String[] differentArray = {};
foo temp = new foo(differentArray);
// Now here is where my problem lies
this = temp;
// out of this I get the following error
// The left-hand side of an assignment must be a variable
}
}
// Let also just say that for the sake of argument, I can't reassign
// 'array' to 'differentArray'
So, how would we make this work? Do I just have to hard code around it or is there a better way to change the reference to the object itself?
Any Advice would be appriciated
You can either mutate the class by reassigning the internal array: instead of String[] differentArray = {}; do array = {};. That will lose the previously stored information.
Or you can return a new foo object:
public Foo reassign() {
Foo temp = new Foo(...);
return temp;
}
Which is appropriate depends on what you are trying to achieve.
Proceed this way:
Foo.java
public class Foo{
// String Array instance
public String[] array; // I made this variable 'public' so that it would be accessible to the main method's class
// Constructor with a String array as a variable to initialize it's instance
public Foo(String[] array){
this.array = array;
}
public void reassign(int length) {
array = new String[length];
array[0] = "Hello"; // String to display in the main() method
}
}
App.java
public class App {
public static void main(String[] args) throws Exception{
String[] tab = new String[1];
tab[0] = "TempValue";
Foo myArray = new Foo(tab);
myArray.reassign(2); // new array with size = 2
System.out.println(myArray.array[0]);
myArray.array[1] = "World";
System.out.println(myArray.array[1]);
}
}
This prints :
Hello
World
to the console. Which proves that the reassign method worked.
Related
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...
I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a toString method ?
package arrays1;
import java.util.Arrays;
public class Arrays1 {
/**
* #param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;
public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];
}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){
numbers[i]=n[i];}
return numbers;
}
public int[] getValues(){
return numbers;
}
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
System.out.println(A.getValues());
}
}
How do I return contents of an array from this code? Do I need to create a new object?
A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
for (int i = 0; i < A.getValues().length; i++){
System.out.println(A.numbers[i]);
}
}
Yes, a toString method would be useful to serialize the contents of the numbers array to a String. But in this case, you should call it like this:
Arrays1 a = new Arrays1(9);
System.out.println(a); // it is an implicit call to toString()
Another acceptable alternative is to let the serialization to the client's responsibility. In this case, the client should rely on the getValues() method, and serialize it by itself:
Arrays1 a = new Arrays1(9);
System.out.println(Arrays.toString(a.getValues()));
Another lesser detail: Review your constructor: It does not use the parameter size, and that can be confusing.
How can I use an array within a method that was called in as a parameter for a different constructor initializer in the same class?
For example:
private static Initialize(int[] array)
private static void Display()
I want to take the array called in above in the Initialize method and use it in the Display method. I kept getting null reference pointer errors when I first tried it. Thank you for any help in advance!!
You can declare your array outside the method Initialize to have access in your class body.
For example:
private static int[] array;
private static Initialize() {
array = new int[] { 1, 2, 3 };
}
private static void Display() {
for (int i : array) {
System.out.println(i);
}
}
Assign the array to a class variable when Initialize() is called.
private static int[] array;
private static Initialize(int[] array) {
this.array=array;
}
The array can then be referenced as array as long as Initialize has already been called.
You probably mean how you can transfer one instance of array between classes.
Simplest way is using simple composition(in this case for one Array, but you can use it on n number of object):
First you need to define new class, which constructor takes in the array data as parameter and define the uninitialized array(which serves as a bridge between classes and also a container for the instantiated data).
public class TransferArray {
private String[] transferredArray;
public TransferArray(String[] originalArray){
transferredArray = originalArray;
}
String[] getArray() {
return transferredArray;
}
}
now to test this work, use this in the main class(both arrays now printing Hello)
String[] originalArray = {"Hello"};
TransferArray transfer = new TransferArray(originalArray);
String[] newArray = transfer.getArray();
System.out.println(originalArray[0]);
System.out.println(newArray[0]);
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.
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];
}
}