Wish List contains

Daestrum

Expert
Licensed User
Longtime User
Is it possible to add the contains method to List

so instead of

B4X:
If myList.indexOf("someValue") <> -1 then ...

becomes
B4X:
If myList.contains("someValue") then ...

I know it's a similar amount of code to write, but it seems clearer using .contains()
 

aeric

Expert
Licensed User
Longtime User
IndexOf want's a object and the "ContainsKey" in a map want's a object too. So why not on the contains function too?
It won't work because if you add a Map or object to the List, it is creating a reference.

edit:
Example
B4X:
    Dim item1 As Map = CreateMap("a": 1)
    Dim item2 As Map = CreateMap("a": 2)
    
    Dim myList As List
    myList.Initialize
    myList.Add(item1)
    myList.Add(item2)
    
    Dim item3 As Map = CreateMap("a": 1)
    Dim item4 As Map = CreateMap("a": 2)
    
    Log(myList.IndexOf(item1) <> -1)    'true
    Log(myList.IndexOf(item2) <> -1)    'true
    Log(myList.IndexOf(item3) <> -1)    'false
    Log(myList.IndexOf(item4) <> -1)    'false
 
Last edited:

LucaMs

Expert
Licensed User
Longtime User
Correct.png
 

aeric

Expert
Licensed User
Longtime User
Yes, I put the comments indicate the Logs output but not my expected results.

I try to explain again if it really not that obvious.

Try:
B4X:
    Log(item3)                            '{a=1}
    Log(myList)                           '[{a=1}, {a=2}]
    Log(myList.IndexOf(item3) <> -1)                ' I expect myList contains {a=1} and returns true but it returns false
    Log(myList.IndexOf(CreateMap("a": 1)) <> -1)    ' same as above

What I want to demonstrate is that the list should contains 2 items, i.e [{a=1}, {a=2}]
If I want to check whether it contains {a=1}, I am expecting it should return true.
 

Daestrum

Expert
Licensed User
Longtime User
@aeric you are correct, .contains() will also fail as item3 (as an object reference) is not in the list.
 

aeric

Expert
Licensed User
Longtime User
Another example for Type:
B4X:
Type Member (name As String, age As Int)

Public Sub CreateMember (name As String, age As Int) As Member
    Dim t1 As Member
    t1.Initialize
    t1.name = name
    t1.age = age
    Return t1
End Sub

Dim Members As List
Members.Initialize
Members.Add(CreateMember("aeric", 21))
Members.Add(CreateMember("mario", 18))

Dim Person As Member
Person.Initialize
Person.name = "aeric"
Person.age = 21

Log("index=" & Members.IndexOf(Person))
 
Top