1

I'm trying to do the following with Java, is this allowed?

import java.util.ArrayList;
class Apple {
    void makeAppleArrayList() {
        ArrayList<String> appleArrayList = new ArrayList<String>();
        appleArrayList.add("apple"); 
        Banana b = new Banana();
        b.copyAppleArrayList(appleArrayList);
    }
}

import java.util.ArrayList;
class Banana {
    ArrayList<String> bananaArrayList = new ArrayList<String>();
    void copyAppleArrayList(ArrayList<String> arrayList) {
        bananaArrayList = arrayList; 
    }
}
3
  • You should try it. Although Banana will just have a reference to Apple's ArrayList in your example. Once you fix your compiler error of course. Have you considered addAll? Commented Dec 12, 2013 at 2:48
  • my bad about insert, just noticed Commented Dec 12, 2013 at 2:49
  • no, i forgot about that, maybe i should try it, thanks for the tip Commented Dec 12, 2013 at 2:50

1 Answer 1

2

Well instead of making an instance of banana in apple why dont you make an instance of apple in banana and just do this:

Apple apple = new Apple();
bananaArrayList = apple.appleArrayList;

So since it is created inside a function you initialize it in the constructor like so:

public class Apple{
public ArrayList<Perk> appleArrayList;

public PerkGenerator() {
        this.appleArrayList = new ArrayList();

And if you do that, there is no need to do it inside a function. But if you still want to do it inside a function. Just keep that code. And do this inside apple:

public ArrayList makeApple(){
    ArrayList apples = new ArrayList();
    return apples;

And then inside of banana you do this:

bananaArrayList = apple.makeApple

This works, because the make apple function returns an arraylist :) Here is some info on returning values from methods :) http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html

Hope i could help :)

Sign up to request clarification or add additional context in comments.

7 Comments

:) Anytime Glad to help out
i just noticed, in apple, the applearraylist is declared within the method, can it still be called like you showed?
As long as you initialize it outside of that method in your constructor. Yes it certainly can. :)
so you mean i need to create a constructor and declare it in that? (sorry im kind of new to all this)
Thats ok :) Ill add it to my answer give me a second :)
|

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.