Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By Sierra

Thread: Returning local objects

  1. #1
    Lowest0ne is offline Member
    Join Date
    Apr 2012
    Posts
    21
    Rep Power
    0

    Default Returning local objects

    I have a class that has 4 lists. I want a method that will return one list that is the "sum" of the 4 lists. The way I envision this is:
    Java Code:
    public List<String> getLists()
    {
      List<String> newList = new List<String>();
      // Add my first list to newList
      // Add my second list to newList
      // Add my third list to newList
      // Add my fourth list to newList
      return newList;
    }
    In C++, this is bad news, the newList is local to the function, and goes out of scope upon return. Is this true with Java as well?

    If so, I should mention that I have made the List class myself, thus I could do some constructor work:
    Java Code:
    public List<String> getLists()
    {
      List<String> newList = new List<String>();
      // Add my first list to newList
      // Add my second list to newList
      // Add my third list to newList
      // Add my fourth list to newList
      return new List<String>(newList.begin(), newList.end());  // Return a copy of the local list
    }
    Any better? Thanks

  2. #2
    Sierra is offline AN21XX
    Join Date
    Mar 2012
    Location
    Munich
    Posts
    297
    Rep Power
    3

    Default Re: Returning local objects

    Hell no, even in C++ you may do it like that if you use pointers of course - only the variable is local, the object remains if created correctly. The point is that this will work fine as java will keep any object as long as it is referenced somewhere.

    Usually you add other lists by using newList.addAll(...) - note however that with that you do not create "New" objects. Every change you do in the old lists will be in the new lists as the objects contained will be the exact same.
    Fubarable likes this.
    I like likes!

Similar Threads

  1. Replies: 12
    Last Post: 04-29-2012, 03:55 PM
  2. Function call returning array of objects
    By ShitalJain in forum New To Java
    Replies: 4
    Last Post: 06-25-2011, 10:39 AM
  3. Replies: 1
    Last Post: 03-05-2011, 06:47 PM
  4. Polygons... returning and passing objects?
    By asherwolf in forum New To Java
    Replies: 3
    Last Post: 07-09-2010, 05:41 PM
  5. Replies: 1
    Last Post: 01-22-2009, 05:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •