Android Question If List1 = List2 doesn't work

Tim Chapman

Active Member
Licensed User
Longtime User
I want to quickly compare two lists to see if they contain the same information.
Why does this code say the lists are equal when they are not?
The log shows List1 = List2.

List1=List2:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    Dim List1 As List
    List1.Initialize
    Dim List2 As List
    List2.Initialize
   
    List1.AddAll(Array As String("value1", "value2"))
    List2.AddAll(Array As String(""))
   
    If List1 = List2 Then
        Log("List1 = List2")
    End If
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 

William Lancee

Well-Known Member
Licensed User
Longtime User
I was curious why @Tim Chapman got the List1 = List2 log.
I had never tried this, so I experimented a bit.

My expectation was that all logs would be 'false', since Dim/Initialize creates different objects.
Curious and curiouser.

B4X:
    Dim List1 As List
    List1.Initialize
  
    Dim List2 As List
    List2.Initialize
  
    Dim List3 As List
    List3.Initialize
  
    Log(List1 = List2)    'true
    Log(List1 = List3)    'true
    Log(List2 = List3)    'true

    List1.Add("AAA")
    List2.Add("AAA")
    List3.Add("BBB")

    Log(List1 = List2)    'true
    Log(List1 = List3)    'false
    Log(List2 = List3)    'false

    List2.Add("XXX")
    Log(List1 = List2)    'false

    List1.Add("XXX")
    Log(List1 = List2)    'true

    List1.Set(0, "ZZZ")
    Log(List1 = List2)    'false

    List2.Set(0, "ZZZ")
    Log(List1 = List2)    'true
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
B4A and B4J.
First we need to know what lists are in Java.

Lists without custom objetos

B4X:
 **using `JavaObject` in B4A** to compare two lists.

---

## 1️⃣ Check if two B4A `List` objects are **exactly equal** (same order + same content)

In B4A, `List` is internally a Java `ArrayList`, so you can call Java methods directly using `JavaObject`.

```basic
Dim l1 As List
Dim l2 As List

l1.Initialize
l2.Initialize

l1.AddAll(Array("A","B","C"))
l2.AddAll(Array("A","B","C"))

Dim jo1 As JavaObject = l1
Dim equal As Boolean = jo1.RunMethod("equals", Array(l2))

Log(equal)  ' True
```

✔ Same size
✔ Same elements
✔ Same order

---

## 2️⃣ Compare lists **ignoring order** (using `containsAll`)

```basic
Dim jo1 As JavaObject = l1
Dim jo2 As JavaObject = l2

Dim sameSize As Boolean = l1.Size = l2.Size
Dim contains1 As Boolean = jo1.RunMethod("containsAll", Array(l2))
Dim contains2 As Boolean = jo2.RunMethod("containsAll", Array(l1))

Dim equal As Boolean = sameSize And contains1 And contains2
```

✔ Order does not matter
⚠️ Not recommended if lists contain duplicates

---

## 3️⃣ Compare using `HashSet` (ignores order and duplicates)

```basic
Dim joSet1, joSet2 As JavaObject

joSet1.InitializeNewInstance("java.util.HashSet", Array(l1))
joSet2.InitializeNewInstance("java.util.HashSet", Array(l2))

Dim equal As Boolean = joSet1.RunMethod("equals", Array(joSet2))
```

✔ Ignores order
✔ Ignores duplicate values

---

## 4️⃣ Get the **difference** between two lists

```basic
Dim diff As List
diff.Initialize
diff.AddAll(l1)

Dim joDiff As JavaObject = diff
joDiff.RunMethod("removeAll", Array(l2))

Log("Only in l1: " & diff)
```

Differences on both sides:

```basic
Dim onlyIn1, onlyIn2 As List
onlyIn1.Initialize : onlyIn1.AddAll(l1)
onlyIn2.Initialize : onlyIn2.AddAll(l2)

Dim jo1 As JavaObject = onlyIn1
Dim jo2 As JavaObject = onlyIn2

jo1.RunMethod("removeAll", Array(l2))
jo2.RunMethod("removeAll", Array(l1))
```

---

## 📌 Quick recommendation

| Goal              | Method          |
| ----------------- | --------------- |
| Exact equality    | `equals()`      |
| Ignore order      | `containsAll()` |
| Ignore duplicates | `HashSet`       |
| Find differences  | `removeAll()`   |
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
Yes, but what does "=" do in B4X?
I've never used the equals sign (=) in list or map comparisons, which, as I mentioned before, is a matter of understanding what lists and maps are in Java.

And especially when the lists or maps contain custom objects.

I think I've seen something about b4x regarding lists or maps, but I haven't used it yet; for now, I'm using javaobject.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
These two subs will work with collections holding "simple" items (strings and numbers):
B4X:
'Tests whether the two maps items are equal. It is based on the 
Public Sub MapsEqual (Map1 As Map, Map2 As Map) As Boolean
    If NotInitialized(Map1) And NotInitialized(Map2) Then Return True
    If NotInitialized(Map1) Or NotInitialized(Map2) Then Return False
    If Map1.Size <> Map2.Size Then Return False
    For Each key As Object In Map1.Keys
        If Map2.ContainsKey(key) = False Then Return False
        Dim v1 As Object = Map1.Get(key)
        Dim v2 As Object = Map2.Get(key)
        If v1 <> v2 Then Return False
    Next
    Return True
End Sub

'Tests whether the two lists items are equal. 
Public Sub ListsEqual (List1 As List, List2 As List) As Boolean
    If NotInitialized(List1) And NotInitialized(List2) Then Return True
    If NotInitialized(List1) Or NotInitialized(List2) Then Return False
    If List1.Size <> List2.Size Then Return False
    For i = 0 To List1.Size - 1
        If List1.Get(i) <> List2.Get(i) Then Return False
    Next
    Return True
End Sub

More complicated cases can be handled with B4XSerializator.
 
Upvote 0
Top