使用Comparator在ArrayList中搜索

时间:2017-08-29 04:22:11

标签: java arraylist collections

我今天接受了采访,并且我已经提供了两个java课程,并要求按注册号搜索狗的详细信息。我知道Java.util.ArrayList.contains(Object)但是当有多个字段时不知道如何实现。

第二个问题是:在这个例子中你可以使用哪种最有效的搜索技术?我想过Collections.binarySearch但不确定它在这个例子中效率最高。如果是这样,我该如何实施呢?

DogSort.java

public class DogSort {

public static void main(String[] args) {
    ArrayList<Dog> listDog = new ArrayList<Dog>();

    Scanner sc = new Scanner(System.in);

    listDog.add(new Dog("Max", "German Shepherd", "33"));
    listDog.add(new Dog("Gracie","Rottweiler","11"));
    Collections.sort(listDog, Dog.COMPARE_BY_NAME);
                System.out.println(listDog);
    }
}

Dog.java

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
};
//getter and setter methods for all private variable

}

3 个答案:

答案 0 :(得分:1)

我同意@Pritam Banerjee的回答。最有效的搜索技术是在此场景中使用HashMap。我建议使用HashSet,但HashSet#contains方法返回boolean,所以只需使用map。这是代码片段。

  

仅供参考使用基于散列的集合/地图时,不要忘记正确实现hashCode和equals方法。

public class DogSearch {
    public static void main(String[] args) {
        Map<String, Dog> dogs = new HashMap<String, Dog>();

        Dog max = new Dog("Max", "German Shepherd", "1001");
        Dog gracie = new Dog("Gracie", "Rottweiler", "1002");
        Dog luca = new Dog("Luca", "Labrador", "1003");
        Dog tiger = new Dog("Tiger", "Beagle", "1004");
        Dog meemo = new Dog("Meemo", "Bulldog", "1005");
        Dog lacie = new Dog("Lacie", "German Shorthaired Pointer", "1006");

        dogs.put(max.getRegistrationNumber(), max);
        dogs.put(gracie.getRegistrationNumber(), gracie);
        dogs.put(luca.getRegistrationNumber(), luca);
        dogs.put(tiger.getRegistrationNumber(), tiger);
        dogs.put(meemo.getRegistrationNumber(), meemo);
        dogs.put(lacie.getRegistrationNumber(), lacie);

        Dog result = dogs.get("1002");

        if (result == null) {
            System.out.println("Dog not found");
        } else {
            System.out.println(result);
        }
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    public String getName() {
        return name;
    }

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

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }

    public void setRegistrationNumber(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((breed == null) ? 0 : breed.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((registrationNumber == null) ? 0 : registrationNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dog other = (Dog) obj;
        if (breed == null) {
            if (other.breed != null)
                return false;
        } else if (!breed.equals(other.breed))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (registrationNumber == null) {
            if (other.registrationNumber != null)
                return false;
        } else if (!registrationNumber.equals(other.registrationNumber))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Dog [name=" + name + ", breed=" + breed + ", registrationNumber=" + registrationNumber + "]";
    }

}

时间复杂度

插入:O(1)

搜索:O(1)

答案 1 :(得分:0)

将其添加到HashMap,注册为Key,Dog object作为值,然后搜索Map

O(1)插入和O(1)搜索。

二进制搜索O(log n)

答案 2 :(得分:0)

对于第一个问题,即按注册号搜索详细信息,这里是代码

import java.util.Comparator;
import java.util.TreeMap;

public class DogSort {

    public static void main(String[] args) {
        TreeMap<Integer, Dog> listDogs = new TreeMap<>();
        listDogs.put(33, new Dog("Max", "German Shepherd", "33"));
        listDogs.put(11, new Dog("Gracie", "Rottweiler", "11"));
        System.out.println(listDogs);
        System.out.println(listDogs.containsKey(11));
        System.out.println(listDogs.get(11));
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    @Override
    public String toString() {
        return "Dog [name=" + name + ", breed=" + breed + ", registrationNumber=" + registrationNumber + "]";
    }

}

使用arraylist通过登记号码得到狗的详细是非常困难的,但是用地图很容易。

你可以像这样覆盖hashcode和equals方法,但是arraylist compare方法的工作方式不同。

您可以做的是编写一种可以按注册号搜索详细信息的方法。该方法必须迭代列表并找到Dog对象,如果列表已排序,那么您需要实现自己的二进制搜索以根据注册号获取Dog对象。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class DogSort {

    public static void main(String[] args) {
        ArrayList<Dog> listDog = new ArrayList<Dog>();

        listDog.add(new Dog("Max", "German Shepherd", "33"));
        listDog.add(new Dog("Gracie", "Rottweiler", "11"));

        Collections.sort(listDog, Dog.COMPARE_BY_NAME);

        System.out.println(listDog);
        System.out.println(listDog.contains(new Dog("Max", "Rottweiler", "33")));
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    @Override
    public String toString() {
        return "Dog [name=" + name + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((registrationNumber == null) ? 0 : registrationNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dog other = (Dog) obj;
        if (registrationNumber == null) {
            if (other.registrationNumber != null)
                return false;
        } else if (!registrationNumber.equals(other.registrationNumber))
            return false;
        return true;
    }


}