Reputation: 76965
I've started writing a class to model a matrix and the compiler gives me this message:
Matrix.java:4: cannot find symbol symbol : constructor Matrix(int[][]) location: class Matrix Matrix y = new Matrix(x);
This is the code that I was trying to compile:
public class Matrix<E> {
public static void main(String[] args) {
int[][] x = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}};
Matrix y = new Matrix(x);
System.out.println(y.getRows());
System.out.println(y.getColumns());
}
private E[][] matrix;
public Matrix(E[][] matrix) {this.matrix = matrix;}
public E[][] getMatrix() {return matrix;}
public int getRows(){return matrix.length;}
public int getColumns(){return matrix[0].length;}
}
So, my question is, why am I getting this error, and what should I change to fix this?
Upvotes: 1
Views: 1654
Reputation: 308988
Try it like this:
public class Matrix<E> {
public static void main(String[] args) {
Integer [][] x = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {0, 1, 0}};
Matrix<Integer> y = new Matrix<Integer>(x);
System.out.println(y.getRows());
System.out.println(y.getColumns());
System.out.println("before: " + y);
Integer [][] values = y.getMatrix();
values[0][0] = 10000;
System.out.println("after : " + y);
}
private E[][] matrix;
public Matrix(E[][] matrix) {this.matrix = matrix;}
public E[][] getMatrix() {return matrix;}
public int getRows(){return matrix.length;}
public int getColumns(){return matrix[0].length;}
public String toString()
{
StringBuilder builder = new StringBuilder(1024);
String newline = System.getProperty("line.separator");
builder.append('[');
for (E [] row : matrix)
{
builder.append('{');
for (E value : row)
{
builder.append(value).append(' ');
}
builder.append('}').append(newline);
}
builder.append(']');
return builder.toString();
}
}
Compiles and runs on my machine.
You need to think about something else: encapsulation and when "private" isn't private. Check out the modification to the code and see how I'm able to modify your "private" matrix.
Upvotes: 2
Reputation: 597324
Try using Integer[][]
instead of int[][]
. Your constructor expects the former (since there are no primitive type arguments), and you are passing the latter.
Upvotes: 1
Reputation: 757
There is no generic array creation in Java. See How to create a generic array in Java?
Upvotes: -2