【发布时间】:2020-01-12 08:58:23
【问题描述】:
如果我将 firstList 元素与 compare 方法进行比较,然后工作正常,结果为 true,但如果我将 secondList 元素与 compare 方法进行比较,则不工作,结果为 false
//**Working case**
List<String> firstList = new ArrayList();
firstList .add("1111111111");
firstList .add("1111333333");
firstList .add("2222224444");
firstList .add("9999888888");
// sout(firstList) : [1111111111, 1111333333, 2222224444, 9999888888]
*System.out.println("first list ::: "+firstList.contains("2222224444")); // true*
// Here i am getting true as expected
// **Not working case** - here final output expected is true but i am getting as false
Map<String,String> elements = new HashMap();
elements.put("user_dids",firstList .toString().replace("[", "").replace("]", ""));
// sout(elements.get("user_dids")) : 1111111111, 1111333333, 2222224444, 9999888888
List<String> secondList = Arrays.asList(elements.get("user_dids"));
//sout(secondList) : [1111111111, 1111333333, 2222224444, 9999888888]
System.out.println(" Second List ::: "+secondList.contains("2222224444")); // false*
// Second list getting false for contains method, but it needs to get true
对于第一个 ArrayList,我为 contains 方法设置为 true,但在第二个 Arraylist 中,也需要为 contains 方法设置为 true,但是 - 我弄错了。
【问题讨论】:
-
谁能帮我解释一下为什么我的 secondList 是假的
-
我想知道是不是因为在调用 toString() 时需要修剪空格
-
使用 System.out.println 打印 secondList 以检查列表是否有这些元素。我怀疑 secondList 没有那个字符串。
-
第二个列表中只有一个元素,字符串
1111111111, 1111333333, 2222224444, 9999888888。secondList.contains()检查一个元素是否等于2222224444,而你的元素不是,所以它返回false。 -
elements.get(...)返回String,Arrays.asList(s)返回一个元素的列表。为什么您认为列表中会包含多个元素?
标签: java arrays arraylist collections hashmap