0

Is it possible to somehow get reference of one array by indexes in java like this pseudocode, for example:

array1 = [1,2,3,4,5,6,7,8] // size 8
array2 = [] // size 4
for(i=0 ; i<4 ; i ++)
{
  array2[i] = reference to array1[random(0,3)]
}

so for example random numbers were 3 0 4 6

array2[0] = array1[3]
array2[1] = array1[0]

and if you change array2[0] to 99 then array1[3]= 99 as well.

5
  • Does this answer your question? Assigning an array reference to another array in Java Commented Jun 2, 2020 at 20:02
  • 1
    Why would random(0,3) generate 6 as a random number? That's outside the 0-3 range. Commented Jun 2, 2020 at 20:07
  • No, it is not possible to "link" array cells like that. What you need to a class wrapping the array(s), so that code in the set() method can perform the appropriate update. Commented Jun 2, 2020 at 20:10
  • It is not possible to do this . Commented Jun 2, 2020 at 20:16
  • Being ripe for race conditions aside, you'll either end up having to update multiple arrays, or you'll have to return array copies (not modifiable by reference). Short of misc.Unsafe/jni, you can't really just have an array pointing to anywhere in memory. Commented Jun 2, 2020 at 20:51

1 Answer 1

0

It's not exactly possible, but you can fake it:

class Reference {

    private Object value;

    public Reference(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value.toString();
    }

    public static Reference[] ofInts(int[] items) {
        Reference[] ret = new Reference[items.length];
        for(int i = 0; i < items.length; ++i) {
            ret[i] = new Reference(items[i]);
        }
        return ret;
    }
}

Then you can use it like this:

int array1[] = new int[] {1,2,3,4,5,6,7,8};
Reference refArray1[] = Reference.ofInts(array1);

final int arr2Size = 4;
Reference refArray2[] = new Reference[arr2Size];
Random rand = new Random();

for(int i = 0; i < arr2Size; ++i) {
    int index = rand.nextInt(array1.length);
    refArray2[i] = refArray1[index];
}

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));
System.out.println("---");

refArray2[0].setValue(99); // set reference value

System.out.println(Arrays.toString(refArray1));
System.out.println(Arrays.toString(refArray2));

Sample output:

[1, 2, 3, 4, 5, 6, 7, 8]
[4, 6, 3, 3]
---
[1, 2, 3, 99, 5, 6, 7, 8]
[99, 6, 3, 3]
Sign up to request clarification or add additional context in comments.

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.