简体   繁体   中英

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

This code in 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. 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 :

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. There is no copy unless you specifically do it.

In this case, Java references will serve more-or-less as a c++ pointer.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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