Deep copying Generics in Java

java deep copy library
java deep copy set
java copy object by value
lombok deep copy
java fastest deep copy
java deep copy with serialization
java map deep copy
java deep copy generic list

I have a programming assignment to make a generic stack in Java and I need to make a deep copy of newNode T. I don't know how to make a method deep Copy that can access its self and output i'`s deep copy. So far, I have this:

public class Stack<T>

    private T[] data;
   private int top;
   private int size;
   public Stack( )
   {  top = -1;
      size = 100;
      data = (T[])new Object[100];
   public Stack(int n)
   {  top = -1;
      size = n;
      data = (T[])new Object[n];
   public boolean push(T newNode)
   {  if(top == size-1)
           return false;  // ** overflow error **
       {  top = top +1;
          data[top] = newNode.deepCopy();
          return true;  // push operation successful
   public T pop( )
   {  int topLocation;
       if(top == -1)
           return null;  // ** underflow error **
       {  topLocation = top;
           top = top -1;
           return data[topLocation];
   public void showAll( )
   {  for(int i = top; i >= 0; i--)


How can I make the deep copy of newNode. I'm pretty sure I need an interface for the method but past that I`m lost.

Perhaps the most general and straight forward solution would consist in asking the using code to provide the deep-copying routine at construction:

public class Stack<T> {
  private final Function<T, T> elementCopier;
  public Stack<T>(Function<T, T> elementCopier) {
     // make sure thy are not passing you a null copier:
     this.elementCopier = Objects.requiresNonNull(elementCopier);
  public boolean push(T element) {
     data[top] = elementCopier.apply(element);

So for example for a cloneable class type where .clone() is in fact a deepCopy the user code would be like:

Stack<MyElemClz> stack = new Stack<>(x -> x.clone());
// or:
Stack<MyElemClz> stack = new Stack<>(MyElemClz::clone);
MyElemClaz elem = ...;

If the type is an constant simple object like and String there is no need for clonning, in that case the user would indicate identity lambda x -> x as the copier:

Stack<String> stack = new Stack<>(x -> x)

If the user insists in making a copy even when the class is a constant you can force it:

Stack<String> stack = new Stack<>(x -> new String(x))
// or
Stack<String> stack = new Stack<>(String::new)

Deep Copy of a Generic Type in Java, This is an example of how to make a generic copy of a class, using Java reflection. In order to make a generic copy of a class we have created  Browse other questions tagged java generics deep-copy or ask your own question. Blog Ben Popper is the worst coder in the world: Something awry with my array

One can use an ObjectOutputStream/ObjectInputStream to make a deep copy. One would then not store an Object (a reference to changeable fields), but the serialized bytes in the stack.

On to it.

An ObjectOutputStream does a deep copy.

Generic deep copy, A Java deep clone (deep copy) example. By Alvin Alexander. Last updated: September 30, 2019. While interviewing for computer programming positions in  Deep copy technique copies each mutable object in the object graph recursively. The object created through  deep copy is not dependent upon the original object. We will cover few different options to make a deep copy of an object in Java. 1.1 Sample Model Classes

If you want to go with an interface, or you don't like Valentin's approach, you could do this:

interface Copiable<T> {
    T deepCopy();

public class Stack<T extends Copiable<T>> {

and then implement the deepCopy method to objects that you put in your stack, i.e.

class A implements Copiable<A> {
  public A deepCopy() {
    // ... your copy code here

Stack<A> stack = new Stack<>();


A Java deep clone (deep copy) example, There are APIs like Java Deep Cloning Library, which make a deep copy using reflection. As I said before this will affect the performance a lot. Is it  Generics in Java. Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well.

Java Deep Copy - Java Copy Object, It also explained the rationale for bringing generics to Java. Part 2 dug deeper into generics by showing you how to codify a generic Stack type,  Generics in Java. The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects.

Immutable Generic Classes, Object is used to create copy or replica of an object. java objects which implement Cloneable interface are eligible for using the clone method. In  A deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy isn't dependent on any mutable object that was created earlier, it won't get modified by accident like we saw with the shallow copy.

Generics 101, Part 3: Exploring Generics Through a Generic Copy , // Method to deep clone an object using in memory serialization. public Employee copy(Person original) throws  Copy Objects in Java In this post, we will discuss various methods to copy objects in Java. Copying an object is creating a copy of an existing object in order to modify or move the copied object without impacting the original object.

  • Welcome to SO. See:… . Is there any additional information about T ? Does it implement the clonable interface ?
  • @c0der: Whether it implements Cloneable or not is irrelevant. Cloneable does not provide a public cloning method; it serves a different purpose.
  • @newacct , Still as pointed by @c0der , some more info about the actual T might helpful , cause when you are trying to deep copy references that have other references it ends to a bad loop.......