Can i take objects from an arraylist in one class and give it to a different class with its own different arraylist
and if so any hints would be loved thanks.
giving ArrayList object to a different ArrayList
Page 1 of 12 Replies - 197 Views - Last Post: 20 June 2012 - 10:14 AM
Replies To: giving ArrayList object to a different ArrayList
#2
Re: giving ArrayList object to a different ArrayList
Posted 19 June 2012 - 12:44 PM
You mean you have two classes, Foo and Bar, each of which has an ArrayList of Widgets, and you want Bar to get Foo's Widgets?
Sure, here's two ways:
And here's a wrong way:
A public ArrayList would allow you to do this, but it's bad design. Don't ever leave fields public.
There are exceptions to this rule, but for now, make all of your fields private.
Sure, here's two ways:
public class Bar
{
private ArrayList<Widget> widgetList; // have to initialize this somewhere
// Foo calls this to submit a widget for Bar's list
public void putWidget(Widget w)
{
widgetList.add(w);
}
// Bar uses this to ask a Foo object to provide a Widget.
private void getWidget(Foo foo)
{
widgetList.add(foo.getWidget());
}
}
And here's a wrong way:
public class Bar
{
public ArrayList<Widget> widgetList; // have to initialize this somewhere
// foo has a reference to bar, and calls bar.widgetList.add(someWidget)
}
A public ArrayList would allow you to do this, but it's bad design. Don't ever leave fields public.
There are exceptions to this rule, but for now, make all of your fields private.
#3
Re: giving ArrayList object to a different ArrayList
Posted 20 June 2012 - 10:14 AM
yes yes thank you
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|