1

I want to create a function to change a value in an array, but I don't want to pass the array to the function. Here is the part of the code, data[] array created at another function.

private int[] data;

public static void main(String[] args) {
    setPixel(3,2); //I'm not sure at this part?
}

public void setPixel(int i,int x){ 
    data[i] = x; //Is there any possible way to change data[]  
}
0

2 Answers 2

2

You should create a class around your main method and instantiate it within main. You then make data a variable of your class and you can access it from within the setPixel() method. This is the proper Object Oriented (OO) way of accomplishing what you're asking.

public class Data {
    private int[] data;

    public Data(int size) {
        data = new int[size];
    }

    public void setPixel(int i, int x) {
        data[i] = x;
    }

    public static void main(String[] args) {
        Data instance = new Data(5);
        instance.setPixel(3, 2);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's my answer, which is pretty much like what @zposten provided, but also address's the OP's data[] array created at another function requirement:

public class EncapsulatedArray
{
    private final int[] data;

    public EncapsulatedArray(final int[] data)
    {
        this.data = data;
    }

    public int getPixel(final int i)
    {
        return data[i];
    }

    public void setPixel(final int i, final int x)
    {
        data[i] = x;
    }

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

To verify and demonstrate, I used:

public class EncapsulatedArrayDemo
{
    public static void main(final String[] args)
    {
        final int[] dataFromElsewhere = { 0, 1, 2, 3 };

        final EncapsulatedArray ex = new EncapsulatedArray(dataFromElsewhere);

        System.out.println(ex);

        ex.setPixel(2, 7 + ex.getPixel(2));

        System.out.println(ex);
    }
}

and obtained the following to console:

{ 0, 1, 2, 3 }
{ 0, 1, 9, 3 }

There are various reasons why wrapper classes like this (toy) example are useful, but if you are hoping to "protect" the data array from outside changes (i.e. only setPixel(int, int) is allowed to modify values in data) then you'll need something more like @zposten's answer which never lets the data array object escape from the wrapper. If you do need to use a data array created at another function then something like my solution is required - but you'll have to take other steps to ensure that the array isn't fiddled with behind the wrapper's back.

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.