2 Replies - 197 Views - Last Post: 20 June 2012 - 10:14 AM Rate Topic: -----

#1 Best_man  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 19-June 12

giving ArrayList object to a different ArrayList

Posted 19 June 2012 - 12:34 PM

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.
Is This A Good Question/Topic? 0
  • +

Replies To: giving ArrayList object to a different ArrayList

#2 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon

Reputation: 5421
  • View blog
  • Posts: 8,707
  • Joined: 19-March 11

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:

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.
Was This Post Helpful? 3
  • +
  • -

#3 Best_man  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 19-June 12

Re: giving ArrayList object to a different ArrayList

Posted 20 June 2012 - 10:14 AM

yes yes thank you
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1