Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Java
  4. Deep copy of List<> without knowing specific list type

Deep copy of List<> without knowing specific list type

Scheduled Pinned Locked Moved Java
functionalquestion
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    jackbrownii
    wrote on last edited by
    #1

    I have some DTOs that are written to be immutable.

    private List foo;
    ... [omitted for brevity]
    public List getFoo() {
    List bar = new ArrayList(foo.size());

    for (Transformation listEntry : foo) {
      bar.add(Transformation.of(listEntry));
    }
    
    return bar;
    

    }

    This works for my current application as I happen to know that the Lists are all ArrayLists. What if I didn't know that? Is there a way to deep copy the contents of an arbitrary implementation of List without knowing what type that underlying List is?

    M 1 Reply Last reply
    0
    • J jackbrownii

      I have some DTOs that are written to be immutable.

      private List foo;
      ... [omitted for brevity]
      public List getFoo() {
      List bar = new ArrayList(foo.size());

      for (Transformation listEntry : foo) {
        bar.add(Transformation.of(listEntry));
      }
      
      return bar;
      

      }

      This works for my current application as I happen to know that the Lists are all ArrayLists. What if I didn't know that? Is there a way to deep copy the contents of an arbitrary implementation of List without knowing what type that underlying List is?

      M Offline
      M Offline
      Manish K Agarwal
      wrote on last edited by
      #2

      As long as ListType is clonable, you can do it as following

      bar.add(listEntry.clone());

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups