【问题标题】:Return the index of an arbitrary Object in a 2d array java.返回二维数组java中任意对象的索引。
【发布时间】:2013-04-17 07:56:17
【问题描述】:

我正在尝试查找放置在数组中的对象的索引。数组已经像这样填充了

for(i = 0 ; i<n ;i++){
    for(j=0; j<n ;j++){
        squares[i][j]= new Square(i,j)
        }

所以数组基本上充满了没有名字的 Square 对象。我想做一个返回方形对象索引的方法,例如:

getObject(Square s){
{

我已经看到其他要求使用的答案

Arrays.asList(array)

还有类似的东西,但它们都试图返回 int 或 String 的索引。

我应该如何返回任何对象的索引?

【问题讨论】:

    标签: java arrays object indexing


    【解决方案1】:

    只要您的Square 的比较运算符(equals() 方法)适合您,那么这些方法中的任何一种都可以工作:

    • 转换为ArrayList 并取消indexOfget
    • 使用java.util.Arrays.binarySearch
    • 执行foreach 循环并手动搜索

    你只需要一个有效的比较运算符,如果默认的Object.equals()(对象实例的比较)适合你的需要,那么你就不用做太多了:

    Point getObject(Square s){
    {
        for(int i = 0; i<n; i++){
            for(int j = 0; j<n; j++){
                if( squares[i][j].equals(s) ) {
                    return Point(i, j);
                }
            }
        }
        return null;
    }
    

    请注意,如果您的数组很大,这不是最快的方法。

    【讨论】:

      【解决方案2】:

      如果你可以使用equals方法(假设n也被定义,或者你可以使用length):

      public int[] getObject(Square s){
      
      int[] returnIndex = new int[2];
      
      for(int i = 0 ; i<this.n ;i++){
          for(int j=0; j<this.n ;j++){ 
      
              if(s.equals(this.squares[i][j])) {
                     returnIndex[0] = i;
                     returnIndex[1] = j;
                     return returnIndex;
                  }
      
             }
          }
          return null;
      }
      

      【讨论】:

        【解决方案3】:

        我已经这样解决了

        private ArrayList<Square> squareList= new ArrayList<Square>(9);
        
          for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        mSquare[i][j] = new Square(i, j);
                        squareList.add(mSquare[i][j]);
                    }
                }
        
            public int index(int r, int c) {
                return squareList.indexOf(Square(r, c));
            }
        

        【讨论】:

          猜你喜欢
          • 2011-04-25
          • 2014-06-27
          • 1970-01-01
          • 2015-04-20
          • 2017-08-16
          • 1970-01-01
          • 2022-01-10
          • 2021-05-01
          • 1970-01-01
          相关资源
          最近更新 更多