简体   繁体   中英

How do I check if an element exists in a queue ( LinkedList ) before adding it?

How do I check if an element exists in a queue ( LinkedList ) before adding it ?

EX: Address [id=1, url=https://www.google.com, size=2, queue=[request [requestId=1], request [requestId=2]]]

I can't add queue=[request [requestId=1], request [requestId=1]] because they have the same requestId.

you can use contains(Object o) method

contains description:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). [...]

Parameters: o – element whose presence in this list is to be tested

Returns: true if this list contains the specified element

LinkedList implements the Collection interface, which defines the Collection#contains method.

You can do what you're after with any class that derives from Collection easily by just using the contains method.

See the docs on LinkedList#contains for more information.

Note: It uses Objects#equals to determine if the item is in the Collection .

If you have the same reference, I think you'll be good. If you have different references representing the same data, then you may need to @Override the equals method on your object.

Below code may help you...

package com.example.Solution;

import java.util.LinkedList;
import java.util.Queue;

public class Sol {
    public static void main(String[] args){
        Queue<Address> q1= new LinkedList<>();
        q1.add(new Address("abc",1,"url1"));
        Address a1=new Address("abc",1,"url");
        if(!q1.contains(a1))
            q1.add(a1);
        Address a2=new Address("abc",2,"url");
        if(!q1.contains(a2)){
            q1.add(a2);
        }
        Address a3=new Address("abc",1,"url2");
        if(!q1.contains(a3)){
            q1.add(a3);
        }
        System.out.println(q1.size());
    }
}
class Address {
    String name;
    int id;
    String url;

    public Address(String name, int id, String url) {
        this.name = name;
        this.id = id;
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
    public boolean equals(Object o1){
        Address address=(Address) o1;
        return address.getId()==this.id;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM