Home » Java » java – Infinite recursion ! how to convert?-Exceptionshub

java – Infinite recursion ! how to convert?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have following classes

class SomeClass{

    private String id;
    private String name;
    private List<SomeClass> history;

}
class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;
}

Now i want a method to convert this SomeClass Object to SomeClassDto.

How to&Answers:

You can create a constructor in SomeClassDTO which takes SomeClass as a parameter and then do the conversion:

class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;

    public SomeClassDto(SomeClass someClass){
        this.name = someClass.getName();
        this.historyDto = new ArrayList<>();
        for(SomeClass sc: someClass.getHistory()){
            this.historyDto.add(new SomeClassDto(sc));
        }
    }
}

Answer:

You should use cache for objects:

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by aprisadkov on 18.02.2020.
 */
public class InfiniteConvert {
    class SomeClass{

        private String id;
        private String name;
        private List<SomeClass> history;

    }
    class someClassDto{

        private String name;
        private List<someClassDto> historyDto;
    }
    HashMap<String, someClassDto> objById = new HashMap();

    public someClassDto convertDto(SomeClass someObj)
    {
        someClassDto ret = objById.get(someObj.id);

        if(ret == null) {
            ret = new someClassDto();
            objById.put(someObj.id, ret);

            ret.name = someObj.name;
            ret.historyDto = someObj.history.stream().map(t -> convertDto(t)).collect(Collectors.toList());
        }
        return ret;
    }

    public static void main(String[] args) throws Exception {
        InfiniteConvert m = new InfiniteConvert();
        m.test();
    }

    public void test()
    {
        SomeClass s1 = new SomeClass();
        s1.id = "1";
        s1.name = "s1";
        SomeClass s2 = new SomeClass();
        s2.id = "2";
        s2.name = "s2";
        SomeClass s3 = new SomeClass();
        s3.id = "3";
        s3.name = "s3";
        SomeClass s4 = new SomeClass();
        s4.id = "4";
        s4.name = "s4";

        s1.history = Arrays.asList(s2,s3,s4);
        s2.history = Arrays.asList(s3,s4);
        s3.history = Arrays.asList(s4);
        s4.history = Arrays.asList(s2,s3,s1);
        someClassDto sn =  convertDto(s1);
    }
}