简体   繁体   English

如何在Java中使用指针(引用)?

[英]How can I use a pointer (reference) in java?

This code in c++ 这段代码在c ++

void generate_moves(char _board[9], std::list<int> &move_list) {
    for(int i = 0; i < 9; ++i) {
        if(_board[i] == 0) {
            move_list.push_back(i);
        }
    }
}

I want to code like that but in java. 我想这样的代码,但在Java中。 How can I do it? 我该怎么做?

void generate_moves(char _board[], List<Integer> move_list) {
    for (int i = 0; i < _board.length; ++i) {
        if (_board[i] == 0) {
            move_list.add(i);
        }
    }
}

The exact translation into Java is : 到Java的确切翻译是:

import java.util.ArrayList;
import java.util.List;

public class Main
{
    public static void main(String[] args)
    {
        char[] board = new char[]
        {
            'o', 'o', 'o',
            'x', 'x', 'x',
            'x', 'x', 'x'
        };

        List<int> moves = new ArrayList<int>();
        generateMoves ( board, moves );
    }

    public static void generateMoves(char[] board, List<int> moves )
    {
        for (int i = 0; i < board.length; ++i)
        {
            if (board[i] == 0)
            {
                moves.add ( i );
            }
        }
    }
}

Because all objects are considered as passed by pointers in Java. 因为所有对象都被视为Java中的指针传递。 There is no copy unless you specifically do it. 除非您专门进行复制,否则没有副本。

In this case, Java references will serve more-or-less as a c++ pointer. 在这种情况下,Java引用将或多或少地用作c ++指针。

public void generate_moves(..., List<Integer> move_list) {
 ...
  move_list.push_back(i);
}

In this case, the invoking push_back on the reference move_list is working exactly like your pointer example. 在这种情况下,在引用 move_list上调用push_back的工作方式与您的指针示例完全相同。 The reference is followed to it's object instance, and then the method is invoked. 该引用遵循其对象实例,然后调用该方法。

What you won't be able to do is access positions in array using pointer arithmetic. 您将无法使用指针算法访问数组中的位置。 That is simply not possible in Java. 在Java中根本不可能做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM