Java how to compare 2 ArrayList of different objects

烈酒焚心 提交于 2019-12-11 09:41:31

问题


I have a problem trying to get an araylist of "tags" in String from 2 ArrayList of objects. I have tried the following but looks like my ideal output is not what I have expected.

Here is the code:

public class TestList {
    public static void main(String []args) {
        Tag tag1 = new Tag();
        tag1.setId(15);
        tag1.setTag("Test");

        Tag tag2 = new Tag();
        tag2.setId(15);
        tag2.setTag("Oracle");

        Tag tag3 = new Tag();
        tag3.setId(16);
        tag1.setTag("OHNO CANNOE");

        List<Tag> tagList = new ArrayList<Tag>();

        tagList.add(tag1);
        tagList.add(tag2);
        tagList.add(tag3);

        System.out.println(tagList.size());

        AnotherTest test1 = new AnotherTest();
        test1.setId(15);
        test1.setTestcol("Another test col");

        AnotherTest test2 = new AnotherTest();
        test2.setId(15);
        test2.setTestcol("HAHAHA");

        List<AnotherTest> anotherTests = new ArrayList<AnotherTest>();
        anotherTests.add(test1);
        anotherTests.add(test2);

        System.out.println(anotherTests.size());
        List<String> getTaglist = new ArrayList<String>();
        for(AnotherTest anotherTest : anotherTests) {
            for(Tag tag: tagList) {
                if(tag.getId()==anotherTest.getId()) {
                    //getTaglist = new ArrayList<String>();
                    getTaglist.add(tag.getTag());
                }
            }
        }

    for (String str: getTaglist) {
        System.out.println(str);
        //this gets:
       //OHNO CANNOE
       //Oracle
       //OHNO CANNOE
       //Oracle
    }

}
}

Why am I not getting "Test" & "Oracle" as my expected result (I am comparing with id ==15 for both lists). Am I missing anything?


回答1:


Tag tag3 = new Tag();
        tag3.setId(16);
        tag1.setTag("OHNO CANNOE");//here is the issue

use

tag3.setTag("OHNO CANNOE");

you are setting tag1 object's property again to "OHNO CANNOE" which will over write the previously written value "test"




回答2:


I believe it is because you are resetting tag1 by doing tag1.setTag as instead of tag3 by doing tag3.setTag, after u define it before u push it into the list



来源:https://stackoverflow.com/questions/22939813/java-how-to-compare-2-arraylist-of-different-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!