java generic calling clone method

Solutions on MaxInterview for java generic calling clone method by the best coders in the world

showing results for - "java generic calling clone method"
Emmanuel
02 Jan 2018
1/* 	If you have a generic class where you want to call your generic object's
2	clone method, add this clone method to your class. */
3
4public class customClass<E extends Cloneable> {
5	private LinkedList<E> lst;
6  
7    public customClass() {
8		// Constructor stuff
9    }
10
11	// Creates a new list with elements starting at index n through end of lst.
12    public LinkedList<E> partialList(int n) {
13		LinkedList<E> parLst = new LinkedList<>();
14        for (int i = n; i < lst.size() - 1; i++) {
15            parLst.add(clone(mlist.get(i))); // Adds deep copied objects to new list.
16        }
17        return parLst;
18    }
19	
20	// The deep copy method for generic object.
21    private E clone(E element) {
22        Class c = element.getClass();
23        
24        try {
25            Method m = c.getMethod("clone", (Class) null);
26            return (E) m.invoke(element, (E) null);
27        }
28        catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
29                | InvocationTargetException e) {
30            return null;
31        }
32    }
33}