CompEng
CompEng

Reputation: 7376

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?

Upvotes: 0

Views: 268

Answers (3)

Alexis Pautrot
Alexis Pautrot

Reputation: 1165

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.

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120168

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.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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

Upvotes: 2

Related Questions