显示数组的输出后,我很遗憾如何调用Generic
方法来确定创建的2D array
的最大数量。
请帮忙
**//Generic method for finding max number**
class Generic {
public static <E extends Comparable<E>> E Max(E[][]list) {
E max = list[0][0];
for (E[] row : list) {
for (E elt : row) {
if (elt.compareTo(max) > 0) {
max = elt;
}
}
}
return max;
}
}
public class GenericTester {
public static void main(String[] args)
{
//creates the grid
final int row = 9;
final int col = 9;
int [][] grid = new int [row][col];
//fills the grid
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = (int)(Math.random()*50);
}
}
//displays the array output
System.out.println("Array : ");
for(int i=0;i<grid.length; i++)
{
for(int j=0; j<grid[i].length; j++)
System.out.print(grid[i][j]+" ");
System.out.println();
};
感谢。
答案 0 :(得分:0)
首先如aiobee int所述,需要转换为Integer Class。然后这是修改后调用函数的代码:
//**//Generic method for finding max number**
class Generic {
public static <E extends Comparable<E>> E Max(E[][]list) {
E max = list[0][0];
for (E[] row : list) {
for (E elt : row) {
if (elt.compareTo(max) > 0) {
max = elt;
}
}
}
return max;
}
}
public class GenericTester {
public static void main(String[] args)
{
//creates the grid
final int row = 9;
final int col = 9;
Integer [][] grid = new Integer [row][col];
//fills the grid
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = Integer.valueOf((int)(Math.random()*50));
}
}
//displays the array output
System.out.println("Array : ");
for(int i=0;i<grid.length; i++)
{
for(int j=0; j<grid[i].length; j++)
System.out.print(grid[i][j]+" ");
System.out.println();
}
Integer max_val = Generic.<Integer>Max(grid);
System.out.println(max_val);
}
}