If indexOf does not find a value (always returns -1)

Asked 1 years ago, Updated 1 years ago, 108 views

I posted a question before, but I couldn't, so I'm uploading it again.

The first method is

ArrayList<HashMap<String,String>> al = new ArrayList<>();
al.add(hm); // hm is Hashmap<String,String> Format
ArrayList<String,String> list = new ArrayList<>();
// // list = [Value1, Value2]
...
HashMap<String,String> hm2 = al.get(0);  // hm2 = {key1=Value1, key2=Value2}
Log.d ("test", String.valueOf(list.indexOf(hm2.get("key1")); // -1 For reference, the return value of hm2.get("key1") is also Value1
Log.d("test",String.valueOf(list.indexOf("Value1")));  // 0

I checked it myself, and hm2.get("key1") is returning a value as String.

Check with .getClass().getName()

But if you put what you brought as get into indexOf, -1, and if you put the return value directly on the code, it returns the index normally, so what's the problem?

android array hashmap

2022-09-22 19:24

1 Answers

Rather, please upload a full source code that can reproduce the error.

The code below must be wrong.

ArrayList<String,String> list = newArrayList<>(); // Incorrect code

Look at the example below. There are no unusual problems.

jshell> ArrayList<HashMap<String,String>> al = new ArrayList<>()
al ==> []

jshell> HashMap<String,String> hm = new HashMap<>()
hm ==> {}

jshell> hm.put("key1", "test")
$8 ==> null

jshell> al.add(hm)
$10 ==> true

jshell> al
al ==> [{key1=test}]

jshell> HashMap<String,String> hm2 = al.get(0)
hm2 ==> {key1=test}

jshell> ArrayList<String> list = new ArrayList<>()
list ==> []

jshell> list.add("test")
$15 ==> true

jshell> String.valueOf(list.indexOf(hm2.get("key1")))
$16 ==> "0"


2022-09-22 19:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.