1

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?

2 Answers 2

5
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"

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.