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

Time:07-26

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

CodePudding user response:

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.

  • Related