【问题标题】:Calling a generic method for finding a max number on a 2D array调用通用方法来查找二维数组上的最大值
【发布时间】:2016-08-22 11:07:59
【问题描述】:

显示数组的输出后,我不知道如何调用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();
    };

谢谢。

【问题讨论】:

  • 你能检查你的代码并给我们完整的格式吗?
  • 泛型不能很好地与基元配合使用。如果您将 gridint[][] 更改为 Integer[][],它将按预期工作。
  • 更改后我应该如何调用以筛选最大数量
  • 你需要最大值还是坐标?

标签: java arrays generics


【解决方案1】:

首先如 aiobee 所说,需要将 int 转换为 Integer 类。然后是调用函数修改后的代码:

//**//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);
}
}

【讨论】:

  • Generic 中的 是否必要。Max(grid) 有必要吗?
  • @ValentinRuano,不,不是。
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 2015-05-09
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
相关资源
最近更新 更多