I have two classes in Java. The first one has functional code. The second one uses ArrayList
s.
How can I get ArrayList
values from the first one?
I am new to Java and programming.
I have two classes in Java. The first one has functional code. The second one uses ArrayList
s.
How can I get ArrayList
values from the first one?
I am new to Java and programming.
If the ArrayList is an instance variable (it's been defined outside of any method, which would make it a local variable) you could simply make it public and it would be visible to your other class. This is not good practise, however. Generally speaking, you would make the ArrayList private and write a getter method that returns a reference to the ArrayList. E.g.
//Declare this at the top of your class
List<?> myList = new ArrayList<>();
public List<?> getMyList(){
return myList;
}
Assuming that the ArrayList is a property of YourClass, then to access it in a method of YourOtherClass you need to create an instance of YourClass:
private void someMethodInYourClass(){
YourClass yourClass = new YourClass();
List<?> yourList = yourClass.getMyList();
}
Having said all that, however, it does seem that you are getting ahead of yourself a bit. The example above is a very basic demonstration of OOP in Java, but it also touches upon generics and collections, which I suspect you are not quite ready for yet. Get yourself a decent beginner's book on Java - there are loads - and bring yourself up to speed before getting in too deep.