0

I'm rewriting program from C++ to Java. In C++ I have two-dimentional array of objects and array of pointers to those objects to sort them. Not every element of the array contains object. I'm new to Java and I'm not sure how to do without pointers yet. This is the piece of code in C++:

Type ** array[SIZE*SIZE];
int k=0;
for(int i=0; i<SIZE; i++)
{
    for(int j=0; j<SIZE; j++)
    {
        if(this->array_of_objects[i][j]!=NULL)
        {
            array[k] = &this->array_of_objects[i][j];
            k++;
        }
    }
}
//then I sort

Java (wrong)

Type array[];

    for(int i=0; i<SIZE*SIZE; i++)
        array[i] = null;

int k=0;
for(int i=0; i<SIZE; i++) {
        for(int j=0; j<SIZE; j++) {
    if(array_of_objects[i][j]!=null) {
                array[k] = array_of_objects[i][j];
                k++;
    }
        }
}
2
  • Can you please show your effort in Java? why do you want to keep the array of pointers? please see any small tutorial to know how java works. Commented May 10, 2014 at 16:37
  • How do you think the Java equivalent would look? Commented May 10, 2014 at 16:37

2 Answers 2

1

Every object in java is managed through references (which could be considered to be a pointer-kind), so you just have to use the value directly :

Type[][] array_of_objects; // array_of_objects[i][j] contains either a value or null

Type[] array = new Type[SIZE * SIZE];
int i = 0;
for (Type[] subarray : array_of_objects) {
    for (Type value : subarray) {
        array[i++] = value;
    }
}

The inner workings with dereferencing and member access is hidden to the programmer and behaves like each variable or array cell is either null or the value directly.

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

Comments

0

Might do that I think looking to list on list java:

List myList = new ArrayList <MyType> (); 
List myList = new ArrayList (); 

creating a custom list.

Comments

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.