简体   繁体   English

将数组列表中的元素分配给这样的字符串是否合法?

[英]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.当我将它放入 eclipse 并运行它时,它抛出了一个异常“无法从 boolean 转换为字符串”,这是我所期待的。 However, the correct answer was "Emad".然而,正确的答案是“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假设包括所有必要的导入和“主要”方法

测试题

This code will set size of aSet to 4:此代码将 aSet 的大小设置为 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.实际上,任何已使用的名称都适用于unknown名称,因为它们将被仅包含唯一值的集合过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM