final 2D array in Java - java

If I initialize an array in a Java method like:
final double[][] myArray = new double[r][c];
Will I be allowed to do this later in the method?
myArray[0] = new double[c];

Yes you can. For more on arrays http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

I'll provide you an example of this:
public class Main {
public static void main(String[] args) {
final int[] finalArray = new int[5];
finalArray[0] = 10;
System.out.println(finalArray[0]);
finalArray[0] = 9001;
System.out.println(finalArray[0]);
finalArray = new int[5] //compile error!!!
}
}
This is because the final modifier will say that the reference to the array (the pointer) can't change, but the elements of the array (that could have another pointer) can change with no problem.
EDIT:
Another example with 2d array:
public class Main {
public static void main(String[] args) {
final int[][] array2d = new int[5][];
for(int i = 0; i < array2d.length;i++) {
array2d[i] = new int[6];
}
//the size of the rows can change with no problem.
array2d[0] = new int[8];
}
}

Related

How to clone array in java with this code

This code generates unsorted array. My question is how do I clone the generated array so I can reuse the unsorted array in different sorting algorithms.
public class UnsortedData{
private int [] coreData;
private int maxArraySize;
private int currentArraySize;
public UnsortedData(int size){
this.maxArraySize = size;
this.coreData = new int[this.maxArraySize];
this.currentArraySize = 0;
}
public boolean addData(int data){
if (currentArraySize < maxArraySize)
{
coreData[currentArraySize] = data;
currentArraySize++;
return true;
}
return false;
}
public class dataSorting {
public static void main(String[] args) {
Random rand = new Random();
UnsortedData uD = new UnsortedData(1000000);
for (int x = 0; x < 50; x++) {
uD.addData(rand.nextInt(3000000));
}
}
Use build in methods from java.lang.Object to clone the original array and java.util.Arrays to sort the cloned array.
int[] arr = {6,9,4,5}; // original array
int[] arrCopy = arr.clone() // we created a copy of the array
Arrays.sort(arrCopy); // it sort the array that we cloned
References: Arrays Class , Class Object
Easiest way? Object.clone()
int[] arr = coreData.clone();
You can also use the Stream API or external libraries such as Apache Commons.

Mysterious error that only appears when declaring the last array

When declaring an array, the IDE (Eclipse) gives me an error. However, if I declare another array immediately after, the error shifts to the next array as if by magic. I can try to add more and more arrays, but I'll only be delaying the inevitable. This leaves me with 2 questions: why does error happen and how do I fix it?
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];//"Syntax error on token ";", { expected
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
public static void main (String[] args) {
}
}
Your for loop must reside in a method of some kind.
For loop itself can't be in a class. The class is just place for declarations, not for code. Code in Java is in methods only.
So you have 2 solutions. Either put your code inside the main method:
import java.util.Arrays;
public class BattleshipGrid {
private static char[][] arr1 = new char[10][10]; // Made it static so that
// it would be bound to the class object itself, so that you can see
// it from the main method which is also static and bound to the class
// object
private static char[][] arr2 = new char[10][10];
private static char[][] arr3 = new char[10][10];
private static char[][] arr4 = new char[10][10];
public static void main (String[] args) {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
}
The other (which is the better) solution is to create an instance of the class inside the main method.
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public void initializeTheGrid() {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
public static void main (String[] args) {
BattleshipGrid grid = new BattleshipGrid();
grid.initializeTheGrid();
}
}
Try something like this:
public class BattleshipGrid
{
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public static void main ( String[] args )
{
for ( char[] i: arr2)
{
for ( char j: i)
{
j = 'X';
}
}
}
}

Issues with arrays and methods

When I'm assigning values to arrays in methods, they become 0 when I try to work with them in other methods.
I'm also not that experienced with programming in java.
Here is my code:
public int[] pVectorCoinOne = new int[2];
public int[] pVectorCoinTwo = new int[2];
public int[] pVectorCoinThree = new int[2];
public int[] pVectorCoinFour = new int[2];
public int[] pVectorCoinFive = new int[2];
public int[] pVectorCoinSix = new int[2];
public void setPositionVectors(){
int[] pVectorCoinOne = {lblCoinImage1.getX(), lblCoinImage1.getY()};
int[] pVectorCoinTwo = {lblCoinImage2.getX(), lblCoinImage2.getY()};
int[] pVectorCoinThree = {lblCoinImage3.getX(), lblCoinImage3.getY()};
int[] pVectorCoinFour = {lblCoinImage4.getX(), lblCoinImage4.getY()};
int[] pVectorCoinFive = {lblCoinImage5.getX(), lblCoinImage5.getY()};
int[] pVectorCoinSix = {lblCoinImage6.getX(), lblCoinImage6.getY()};
}
public void printAllToOutput(){
setPositionVectors();
System.out.println(Arrays.toString(pVectorCoinOne));
System.out.println(Arrays.toString(pVectorCoinTwo));
System.out.println(Arrays.toString(pVectorCoinThree));
System.out.println(Arrays.toString(pVectorCoinFour));
System.out.println(Arrays.toString(pVectorCoinFive));
System.out.println(Arrays.toString(pVectorCoinSix));
}
Fix like this:
public void setPositionVectors(){
pVectorCoinOne[0] = lblCoinImage1.getX(); //example
}
It is all about scope - local vs global. And you cannot set the array directly like this. In java, you can set constants to array only during initialization.
like:
public int[] array = {1, 2};
When you write
public void setPositionVectors(){
int[] pVectorCoinOne = {lblCoinImage1.getX(), lblCoinImage1.getY()};
int[] pVectorCoinTwo = {lblCoinImage2.getX(), lblCoinImage2.getY()};
int[] pVectorCoinThree = {lblCoinImage3.getX(), lblCoinImage3.getY()};
int[] pVectorCoinFour = {lblCoinImage4.getX(), lblCoinImage4.getY()};
int[] pVectorCoinFive = {lblCoinImage5.getX(), lblCoinImage5.getY()};
int[] pVectorCoinSix = {lblCoinImage6.getX(), lblCoinImage6.getY()};
}
the method initializes new local variables with the same names inside its own rather than calling the ones you declared above. So the variables will disappear when the method ends, and nothing will be changed.

Java - Change values of an array by a method in a Class

Here is my code:
class Myclass {
private static int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
int[] array = new int[10];
}
}
It throws a java.lang.nullPointerException when trying to do this:
m.array[i] = i;
Can anybody help me please?
You have declared a local variable array in your constructor, so you're not actually initializing the array declared in Myclass.
You'll want to refer directly to array in the constructor. Instead of
int[] array = new int[10];
Use this
array = new int[10];
Additionally, you've declared array static in the scope of your Myclass class.
private static int[] array;
You only have one instance of Myclass here, so it doesn't matter, but normally this would not be static, if you're initializing it in a constructor. You should remove static:
private int[] array;
In your constructor you are making your assignment to a local variable names array, not the static class variable also named array. This is a scope problem.
I'm also guessing that since you access array via m.array, you want a member variable and not a static one. Here's the fix
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
rray = new int[10];
}
}
in MyClass() type this
this.array = new int [10];
instead of this
int[] array = new int[10];
Your code should be as below. In the constructor, instead of initializing the instance variable you created a new local variable and the instance variable was left uninitalized which caused the NullPointerException. Also the instance variable shouldn't be static.
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
array = new int[10];
}
}
First, if you plan to use array as a field of m (i.e. m.array) don't declare it as static, but:
private int[] array;
Next thing you have to do is to initialize it. Best place to do that is in the constructor:
public MyClass() {
array= new int[10]; //just array = new int[10]; don't put int[] in front of the array, because the variable already exists as a field.
}
The rest of the code should work.

How to put array in an object in Java?

I am trying to clone an array and return as an object, not an array type.
z
public IntVector clone()
{
IntVector cloneVector = new IntVector(3);
int[] newItems = new int[10];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
cloneVector = newItems; // is there a way to do something like this??
return cloneVector;
}
Main method looks like this
public static void main(String[] args)
{
IntVector vector = new IntVector(5);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
}
*there are two other methods which makes an array:IntVector() and puts value into array:push()
Declare a new constructor for IntVector which takes an int array and a count:
IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
Then you can write clone like this:
public IntVector clone() {
return new IntVector(items_, itemCount_);
}
You can make that new constructor private if you like, so only clone can use it.

Categories