Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it legal to assign elements from an array list to a string like this?

When I put this into eclipse and ran it, it threw an exception "cannot convert from boolean to String" which is what I was expecting. However, the correct answer was "Emad". I don’t see how this code would be able to run without an error.

It’s assumed all essential imports and ‘main’ method are included

Test Question

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This code will set size of aSet to 4:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<String> alist = new ArrayList<>();
        String unknown = "Emad";
        alist.add("Adam");alist.add("Emad");
        alist.add("Eve");alist.add("Jim");
        alist.add("Jim");alist.add("Eve");
        alist.add(unknown);
        HashSet<String> aSet = new HashSet<>(alist);
        System.out.println(aSet.size());
    }
}

Actually, any already used names will work for unknown as they will be filtered by set which can contain only unique values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading