No remove Items in ArrayList

Hey guys, I’m new to Kotlin and I’m practicing ArrayList. I can’t get it to delete the item I select. Can someone help me?
Thanks a lot.
package com.example.pruebas.oop.clases

import kotlin.String

class Producto (val id:String?=“”, val detalle:String?=“”, val pciounit:Double?=0.00, val pciovta:Double?=0.00, val rubro: Int?=0) {

val productoArray = ArrayList<Producto>()

fun alta(item: Producto) {
    productoArray.add(item)
}

//***********baja
fun baja(item:Producto) {
if (productoArray.contains(item)) {
productoArray.remove(item)
println(“true”)

    } else {println("false")
        println(item.id)
    }
}

fun ver() {
    println(productoArray.size)
    for (x in productoArray) {
        println("${x.id} ${x.detalle} ${x.pciounit} ${x.pciovta} ${x.rubro}")
    }
}

}

fun main(){
val producto=Producto()
alta(producto)
baja(producto)
}

fun alta(prod:Producto) {
prod.alta(Producto(“001”, “Etchard Blanco x 1000cc”, 5.01, 6.25, 1))
prod.alta(Producto(“002”, “Zucardi Tinto x 1000cc”, 6.54, 7.15, 1))
prod.alta(Producto(“003”, “Mirk Tinto x 750cc”, 6.33, 7.33, 1))
/* producto.alta(Producto(“004”, “Bless Rosado x 750cc”, 6.56, 7.25, 1))
producto.alta(Producto(“005”, “Mel Tinto x 1000cc”, 5.15, 7.38, 1))
producto.alta(Producto(“006”, “Etchar Blanco x 750cc”, 4.34, 6.38, 2))
producto.alta(Producto(“007”, “Toro Blanco x 1000cc”, 6.78, 7.38, 2))
producto.alta(Producto(“008”, “Tupungato Blanco x 750cc”, 3.23, 5.38, 2))
producto.alta(Producto(“009”, “Bizterry Blanco x 1000cc”, 4.55, 8.38, 2))
producto.alta(Producto(“010”, “Rivoli Blanco x 350gr”, 4.34, 6.38, 3))
producto.alta(Producto(“011”, “Wero Blanco x 500gr”, 6.78, 7.38, 3))
producto.alta(Producto(“012”, “Palmiro Blanco x 350gr”, 3.23, 5.38,3))
producto.alta(Producto(“013”, “Tiken Blanco x 500gr”, 4.55, 4.55, 3))
*/
prod.ver()
}

fun baja(prod:Producto){
prod.baja(Producto(“003”, “Mirk Tinto x 750cc”, 6.33, 7.33, 1))
prod.ver()

}

Try making your class: data class Producto. Explanation: Java/Kotlin by default don’t compare objects by value, but by identity. We need to ask explicitly for comparing by value, either by implementing equals (and hashCode) or using a data class.

Anyway, this code is very inefficient. ArrayList is not really suited for searching in it and removing items in the middle. For this case we have sets or maps. But I guess it doesn’t matter for learning purposes.

2 Likes

For the future, please format your code either using the code button </> or by surrounding it in three backticks ``` so that it displays nicely and can be read and copied way easier

1 Like

Hi, thanks, I’m learning. And which would you recommend, a set or a map? The idea is to simulate SQL queries and save them in maps or sets, and relate them, and insert, delete, and modify (within the map or set). Could you recommend one and if you have a simple example? Thank you very much.