如何正确地将对象显示为String

W M*_*W M 4 java tostring

我正在研究这个代码,并希望打印一个矩阵,但那就是出现了什么 Matrix@2c78bc3b Matrix@2a8ddc4c

这是一个代码示例:

public class Matrix
{

    public static int rows;
    public static int colms;//columns
    public static int[][] numbers;

    public Matrix(int[][] numbers)
    {

        numbers = new int[rows][colms];

    }


    public static boolean isSquareMatrix(Matrix m)
    {
        //rows = numbers.length;
        //colms = numbers[0].length;

        if(rows == colms)
           return true;
        else
            return false;
    }

    public static Matrix getTranspose(Matrix trans)
    {
       trans = new Matrix(numbers);

        for(int i =0; i < rows; i++)
        {
            for(int j = 0; j < colms; j++)
            {
                trans.numbers[i][j] = numbers[j][i];
            }
        }
        return trans;
    }



    public static void main(String[] args)
    {
        int[][] m1 = new int[][]{{1,4}, {5,3}};
        Matrix Mat = new Matrix(m1);

        System.out.print(Mat);
        System.out.print(getTranspose(Mat));

    }
}
Run Code Online (Sandbox Code Playgroud)

and*_*soj 7

您需要以toString()有意义的方式实施.

这个toString()(下面)可能适合于调试,但如果你将它用于真正的用户输出,那将会很难看并且令人困惑.实际的解决方案可能会Formatter以某种复杂的方式使用整齐的表格行和列.

基于您的代码的一些其他建议:

  • 建议不要单独存储行/列大小. SSOT /单一真实来源DRY,Java + DRY.只需使用.length,并在需要时提供访问器方法.
  • final在方法args中使用它会消除上面的numbers错误,在构造函数中输入错误
  • 使用实例,而不是 static
  • 偏执狂是程序员的生活方式:我还修改了我的代码以执行deepCopy提供的int[][]数组,否则会出现引用泄漏,Matrix如果调用者代码稍后修改了int[][]它们传入,则类将无法强制执行其自己的不变量.

  • 出于习惯,我Matrix不可改变(见final private numbers[][]).这是一个很好的做法,除非你提出了一个可变实现的充分理由(由于矩阵中的性能原因,这并不奇怪).

这是一些改进的代码:

public final class Matrix
{
    final private int[][] numbers;

    // note the final, which would find a bug in your cited code above...
    public Matrix(final int[][] numbers)
    {   
        // by enforcing these assumptions / invariants here, you don't need to deal 
        // with checking them in other parts of the code.  This is long enough that you might 
        // factor it out into a private void sanityCheck() method, which could be 
        // applied elsewhere when there are non-trivial mutations of the internal state

        if (numbers == null || numbers.length == 0) 
          throw new NullPointerException("Matrix can't have null contents or zero rows");
        final int columns = numbers[0].length;
        if (columns == 0) 
          throw new IllegalArgumentException("Matrix can't have zero columns");
        for (int i =1; i < numbers.length; i++) {
          if (numbers[i] == null) 
             throw new NullPointerException("Matrix can't have null row "+i);
          if (numbers[i].length != columns) 
             throw new IllegalArgumentException("Matrix can't have differing row lengths!");
        }
        this.numbers = deepCopy(numbers);
    }

    public boolean isSquareMatrix() { return rowCount() == columnCount(); }
    public int rowCount() { return numbers.length; }
    public int columnCount() {return numbers[0].length; }

    private static int[][] deepCopy(final int[][] source)
    {
       // note we ignore error cases that don't apply because of 
       // invariants in the constructor:
       assert(source != null); assert(source.length != 0);
       assert(source[0] != null); assert(source[0].length != 0);
       int[][] target = new int[source.length][source[0].length];
       for (int i = 0; i < source.length; i++) 
          target[i] = Arrays.copyOf(source[i],source[i].length);
       return target;
    }

  public Matrix getTranspose()
  {

    int[][] trans = new int[columnCount()][rowCount()];

    for (int i = 0; i < rowCount(); i++)
      for (int j = 0; j < columnCount(); j++)
        trans[i][j] = getValue(j, i);
    return new Matrix(trans);
  }

  @Override
  public String toString()
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < numbers.length; i++) 
    { 
      for (int j = 0; j < numbers[i].length; j++) 
        sb.append(' ').append(numbers[i][j]);
      sb.append('\n');
    }
    return sb.toString();
  }

  public static void main(String[] args)
  {
    final int[][] m1 = new int[][] { { 1, 4 }, { 5, 3 } };
    Matrix mat = new Matrix(m1);
    System.out.print(mat);
    System.out.print(mat.getTranspose());
  }
}
Run Code Online (Sandbox Code Playgroud)