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];
}
Related
I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)
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
}
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.
I am having a little trouble understanding the concept of final in Java.
I have a class that follows:
public class MyClass
{
private int[][] myArray; // intended to be changed
private final int[][] MYARRAY_ORIGINAL; // intended to be unchangable
public MyClass(int[][] array)
{
myArray = array;
MYARRAY_ORIGINAL = array;
}
}
I was under the understanding that final would make MYARRAY_ORIGINAL read only. But I have tried editing myArray, and it edits MYARRAY_ORIGINAL as well. My question is, in this context, what exactly does final do? And for extra credit, how can I copy the array passed through the constructor into MYARRAY_ORIGINAL so that I can have 2 arrays, one to edit, and one that will remain preserved?
Your final MYARRAY_ORIGINAL is indeed read only: you can't assign a new value to the MYARRAY_ORIGINAL reference in other side than class constructor or attribute declaration:
public void someMethod() {
//it won't compile
MYARRAY_ORIGINAL = new int[X][];
}
The values inside the array are not final. Those values can change anytime in the code.
public void anotherMethod() {
MYARRAY_ORIGINAL[0][0] = 25;
//later in the code...
MYARRAY_ORIGINAL[0][0] = 30; //it works!
}
If you indeed need a List of final elements, in other words, a List whose elements can't be modified, you can use Collections.unmodifiableList:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
The last piece of code was taken from here: Immutable array in Java
In case of Objects, final makes reference can't be changed, but object state can be changed.
That is the reason why you are able to change values of final MYARRAY_ORIGINAL
MYARRAY_ORIGINAL is indeed read only variable. Your array reference can not be assigned a new value nor for their length of the arrays can be changed. A final variables initialization can be deferred till the constructors is called. If one tries to modify the reference of the final variable, compiler will throw an error message. But what is possible is, one can edit the elements of the MYARRAY_ORIGINAL and of the myArray i.e one can change the state of the object assigned to a final variable. For example
Class A {
final int[] array;
public A() {
array = new int[10] // deferred initialization of a final variable
array[0] = 10;
}
public void method() {
array[0] = 3; // it is allowed
array = new int[20] // not allowed and compiler will throw an error
}
}
To understand more on final please take a look at Java Language Specification on final variable.
Final does not mean 'read-only' per se, but more so "safe publication' for other threads than the one to which it is defined. Another aim of 'final' is that it ensures the latest object available in a multi-thread environment.
Secondly, if you define something as "final", for example:
private final int[][] MYARRAY_ORIGINAL;
The reference is "final", but not the object itself. A much better way to understand it would be this:
public static final List myList = new ArrayList();
Now I can access myList from any other threads - I can modify it (add to it); but I cannot
(a) Declare it again - myList = new ArrayList();
(b) Assign it another list - myList = anotherList;
The context for final I would see best, in a multiple-thread scenario.
Bonus: to answer your question, you cannot make a 'readonly' array, you will have to manage that yourself (as final, only maintains 'read-only' to reference not object)
You can use the method System.arraycopy to make a copy of the array as follows -
int[][] source = {{1,2},{3,4}};
int[][] copy = new int[source.length][];
System.arraycopy(source, 0, copy, 0, source.length);
Also, you some problem with your code regarding what you are trying to do. If you look at the constructor
public MyClass(int[][] array) { //something else passes the array
myArray = array;
MYARRAY_ORIGINAL = array; // you are just keeping a reference to it can be modified from outside
}
If you really want nobody to modify the values in that array MYARRAY_ORIGINAL, you should make a copy of the source array that comes comes from outside.
public MyClass(int[][] array) {
myArray = array; //make a copy here also if you don't want to edit the argument array
MYARRAY_ORIGINAL = new int[array.length][];
System.arraycopy(array, 0, MYARRAY_ORIGINAL, 0, array.length);
}
Now you shouldn't have to worry about the array's being modified from outside.