Java - How to access an ArrayList of another class?

后端 未结 5 513
感动是毒
感动是毒 2020-12-23 18:11

Hello I\'m a beginner in Java and this is my question: I have this first class with the following variables:

import java.util.ArrayList;

public class number         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 18:49

    Put them in an arrayList in your first class like:

    import java.util.ArrayList;
        public class numbers {
    
        private int number1 = 50;
        private int number2 = 100;
    
        public ArrayList getNumberList() {
            ArrayList numbersList= new ArrayList();
            numbersList.add(number1);
            numberList.add(number2);
            ....
            return numberList;
        }
    }
    

    Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

    You can also access a variable declared in one class from another simply like

    numbers.numberList;
    

    if you have it declared there as public.

    But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

    If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

提交回复
热议问题