Home > Back-end >  How to edit an array from another class
How to edit an array from another class

Time:09-14

Hey all first time im on here.

Pretty much I want to declare an array in one class, then in another class determine the size of said array through user input, is this possible? Ive tried however it doesnt seem like anything is working.

Any help is useful!

Regards

CodePudding user response:

Certainly you can. Though you should think twice before sharing state (such as your array) between classes.

Here is a rather screwball but simple example.

We locally define two classes as records.

  • One class holds an array of int values.
  • The other class contains a reference to an object of that array holder class. This tracking class offers a method that reaches into that contained array holder object, accesses its array, and determines the length of its contained array.
record ArrayHolder( int[] array ) { }
record ArraySizeTracker( ArrayHolder arrayHolder )
{
    int size ( ) { return this.arrayHolder.array.length; }
}

ArrayHolder holder = new ArrayHolder( new int[] { 7 , 42 } );
ArraySizeTracker tracker = new ArraySizeTracker( holder );

System.out.println( "tracker.size(): "   tracker.size() );

2

Again, such intermingling of state between classes is usually a sign of flaw in your class design. So I would never use such an arrangement in real work. But it does serve as a demo to answer your Question.

CodePudding user response:

First time coding Java in about a year so sorry if some syntax is off, but this should do it!

    import java.util.Scanner;  

    public class main {
       public static void main(String[] args) {
          // Get user input
          Scanner s = new Scanner(System.in);
          System.out.print("Array Size: ");
          int size = s.nextInt();
          // Create an array to pass into test object
          int[] actualArray = new int[10];
          // Create test object and pass in the array
          Test t1 = new Test();
          t1.setMyArray(actualArray);
       }

    }

    class Test {
        private int[] myArray;
        public void setMyArray(int[] myArray) {
            this.myArray = myArray;
        }
    }

The idea here is that we simply are passing the reference to actualArray in memory. This allows Test to access this array using the reference now saved in myArray. Hope this helps! (P.S you can edit the values through myArray inside of test or actualArray inside of main. They both refer to the same memory so changing one changes the other.

  • Related