Java 如何删除类的arraylist中的重复项

Java 如何删除类的arraylist中的重复项,java,android,kotlin,Java,Android,Kotlin,我正在尝试将服务器上的数据放到我的应用程序中, 使用RecyclerView和volley,正因为如此,我使用了一个适配器,这是我的适配器类 class TypeAdapter(var con: Context, var list: ArrayList<TypeItems>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onBindViewHolder(p0: RecyclerView.

我正在尝试将服务器上的数据放到我的应用程序中, 使用RecyclerView和volley,正因为如此,我使用了一个适配器,这是我的适配器类

class TypeAdapter(var con: Context, var list: ArrayList<TypeItems>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onBindViewHolder(p0: RecyclerView.ViewHolder, p1: Int) {

    (p0 as ItemView).bind(list[p1].cartype, list[p1].typetype, list[p1].modeltype, list[p1].photype)

}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): RecyclerView.ViewHolder {
    val v= LayoutInflater.from(con).inflate(R.layout.car_model_item, p0, false)

    return ItemView(v)
}

override fun getItemCount(): Int {
    return list.size
}

class ItemView(itemVeiw: View) : RecyclerView.ViewHolder(itemVeiw) {

    fun bind(car_type: String, type: String, modele: String, ph: String) {

        Picasso.with(itemView.context).load(ph).into(itemView.type)

        itemView.name.text= "$car_type $type"
        itemView.model.text= modele


    }
}
}
这是我的主课

class CarModelActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_car_model)

    val list= ArrayList<TypeItems>()

    val rq= Volley.newRequestQueue(this)

    val  url= ("http://test123456789.cf/sell_items/reportall.php?car_type=${car_item.cartype}").replace(" ", "%20")

    val srr= StringRequest(Request.Method.GET, url ,
        Response.Listener { response ->

            //converting the string to json array object
            val array = JSONArray(response)

            list.clear()

            //traversing through all the object
            for (i in 0 until array.length()) {

                //getting item object from json array
                val product = array.getJSONObject(i)


                //ex Image
                var url2= "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRj3LA1ERJCx8lM-qHsgaW_5IgzeW21w-Ona7iI05E9aoXrImtl"

                //adding the product to item list
                list.add(
                    TypeItems(
                        product.getString("car_type"),
                        product.getString("type"),
                        product.getString("model"),
                        url2
                    )
                )

            }

            //creating adapter object and setting it to recyclerview
            val adapter = TypeAdapter(this.applicationContext, list)
            rv.layoutManager= GridLayoutManager(this, 2)
            rv.adapter = adapter

        }, Response.ErrorListener { error ->
            Toast.makeText(this, error.message, Toast.LENGTH_LONG).show()
        })

    rq.add(srr)

}
}
class CarModelActivity:appcompativity(){
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity\u汽车模型)
val list=ArrayList()
val rq=Volley.newRequestQueue(此)
val url=(“http://test123456789.cf/sell_items/reportall.php?car_type=${car_item.cartype}”)。替换(“,“%20”)
val srr=StringRequest(Request.Method.GET,url,
Response.Listener{Response->
//将字符串转换为json数组对象
val数组=JSONArray(响应)
list.clear()
//遍历所有对象
for(在数组.length()之前0中的i){
//从json数组获取项对象
val product=array.getJSONObject(i)
//前图像
变量url2=”https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRj3LA1ERJCx8lM-qHsgaW_5IgzeW21w-Ona7iI05E9aoXrImtl“
//将产品添加到项目列表
list.add(
类型项(
product.getString(“汽车类型”),
product.getString(“类型”),
product.getString(“模型”),
url2
)
)
}
//创建适配器对象并将其设置为recyclerview
val adapter=TypeAdapter(this.applicationContext,list)
rv.layoutManager=GridLayoutManager(这个,2)
rv.适配器=适配器
},Response.ErrorListener{error->
Toast.makeText(this,error.message,Toast.LENGTH\u LONG.show())
})
rq.add(srr)
}
}


现在我想从列表中删除重复的项目,我想按车辆类型、类型和型号进行排序,如果项目重复,我想删除它

val list=ArrayList()
替换为
val set=SortedSet()

和覆盖等于类型项的方法:

override fun equals(other: Any?): Boolean {
    if (other is TypeItems) {
        other.cartype == this.cartype && ... // replace TypeItems fields
    } else {
        false
    }
}
此外,如果您想要排序,TypeItems必须实现
Compariable

您应该使用数据类。它将在内部包含重写的
equals()
方法:

data class TypeItems(
    val car_typetype: String,
    val typetype: String,
    val modeletype: String,
    val phtype: String
)
在深入研究这个问题之后,我发现,您无法调用
Set
集合上的方法
get()
。因此,此代码将不起作用:
(p0作为ItemView).bind(列表[p1]。cartype,列表[p1]。typetype,列表[p1]。modeltype,列表[p1]。photype)

总之,
Set
对您没有帮助。要解决问题,只需调用防御检查:

val typeItems = TypeItems(
                product.getString("car_type"),
                product.getString("type"),
                product.getString("model"),
                url2
        )
        if(!list.contains(typeItems)) {
            list.add(typeItems)
        }
因此,有另一种方法来解决这个问题: 而不是
val adapter=TypeAdapter(this.applicationContext,list)

援引
val adapter=TypeAdapter(this.applicationContext,list.distinct())


方法
distinct()
按相同顺序返回列表的唯一值。不过,别忘了将其设为数据类

请注意,接受的答案建议在可能将元素添加到列表之前使用
list.contains(x)
。但是,
contains
接受O(n),并且您正在对响应中得到的每个项目进行检查,因此总复杂度为O(n^2)。如果您有许多项,那么性能可能非常差,这意味着您的应用程序可能没有响应,用户体验可能会受到影响。此外,项目是按插入顺序排序的,因此我们需要按照所需的顺序显式地对其进行排序——至少添加另一个O(n*log(n)),这一顺序虽然由前一个O(n^2)控制

正如@Rogue和@taha所建议的那样,
TreeSet
因此可能更适合这个特定的用例,因为它自动防止重复,插入时的复杂性为O(log(n)),并且它强制执行某种排序

下面是一个如何使用它的示例:

data class TypeItems(
    val car: String,
    val type: String,
    val model: String,
    val ph: String
)

fun main() {
    // simulates a response from the server
    val response = listOf(
        TypeItems("carBBB", "typeBBB", "modelBBB", "phBBB"),
        TypeItems("carAAA", "typeAAA", "modelAAA", "phAAA"),
        TypeItems("carAAA", "typeAAA", "modelAAA", "phAAA"),
        TypeItems("carCCC", "typeZZZ", "modelYYY", "phCCC"),
        TypeItems("carCCC", "typeXXX", "modelWWW", "phCCC"),
        TypeItems("carCCC", "typeXXX", "modelVVV", "phCCC")
    )

    // creates an empty TreeSet with the desired sorting
    val set = TreeSet<TypeItems>(
        Comparator.comparing(TypeItems::car)
            .thenComparing(TypeItems::type)
            .thenComparing(TypeItems::model)
            .thenComparing(TypeItems::ph) // needed for "consistency with equals"
    )

    // add each element to the set, it'll handle duplicates
    response.forEach { set.add(it) }

    // do something with the resulting set: print each item on a new line
    set.forEach {
        println(it)
    }
}

使用
LinkedHashSet
类,既可以禁止重复,也可以保留代码中项目的顺序<代码>哈希集本身并不能保证排序,而且在相当多的情况下,您的项目看起来是随机的。我不是kotliner,所以虽然我不能用纯Java来代表数据类,但你应该重写#equals和#hashcode来匹配这是怎么回事?我无法调用SortedSet上的列表[0]。对于已排序的数据集,
TreeSet
将是我的目标set@samaromku首先,非常感谢您的帮助,但您能向我解释一下发生了什么,什么是数据类吗
data class TypeItems(
    val car: String,
    val type: String,
    val model: String,
    val ph: String
)

fun main() {
    // simulates a response from the server
    val response = listOf(
        TypeItems("carBBB", "typeBBB", "modelBBB", "phBBB"),
        TypeItems("carAAA", "typeAAA", "modelAAA", "phAAA"),
        TypeItems("carAAA", "typeAAA", "modelAAA", "phAAA"),
        TypeItems("carCCC", "typeZZZ", "modelYYY", "phCCC"),
        TypeItems("carCCC", "typeXXX", "modelWWW", "phCCC"),
        TypeItems("carCCC", "typeXXX", "modelVVV", "phCCC")
    )

    // creates an empty TreeSet with the desired sorting
    val set = TreeSet<TypeItems>(
        Comparator.comparing(TypeItems::car)
            .thenComparing(TypeItems::type)
            .thenComparing(TypeItems::model)
            .thenComparing(TypeItems::ph) // needed for "consistency with equals"
    )

    // add each element to the set, it'll handle duplicates
    response.forEach { set.add(it) }

    // do something with the resulting set: print each item on a new line
    set.forEach {
        println(it)
    }
}
TypeItems(car=carAAA, type=typeAAA, model=modelAAA, ph=phAAA) // duplicate removed
TypeItems(car=carBBB, type=typeBBB, model=modelBBB, ph=phBBB) // car order enforced (as B > A)
TypeItems(car=carCCC, type=typeXXX, model=modelVVV, ph=phCCC) // type order enforced (as X > B)
TypeItems(car=carCCC, type=typeXXX, model=modelWWW, ph=phCCC) // model order enforced (as W > V)
TypeItems(car=carCCC, type=typeZZZ, model=modelYYY, ph=phCCC)