0

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?

3

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, all objects are pass by value reference. Also, char[] board = new char[] { ... }; can be shortened to char[] board = { ... }.
Why does the int become a String?
2
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);
        }
    }
}

1 Comment

@PeterLawrey - I probably would as well. Both styles work, of course, and C++ programmers might be more comfortable with the trailing []. I also don't know what meaning the underscore in the parameter name has to OP.
0

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.

8 Comments

Java references serve more or less as C++ references, not C++ pointers.
thanks for answering. I want to learn move_list.pushback() does not defined. Why?
@tedd, based on the differences outlined here, I have to completely disagree. en.wikipedia.org/wiki/Reference_(C%2B%2B)
@Ersin, you have to define that method. My code is not valid; just a guide
move_list.push_back(i); means move_list.addLast(i); or move_list.add(i)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.