Java比较对象

时间:2015-12-07 03:24:34

标签: java arrays

我正在尝试创建一个二进制搜索程序,它可以使用各种类型的变量(整数,浮点数,字符串等)来查看数组中是否存在元素。我想弄清楚如何比较变量。这是我正在使用的草图:

import java.util.ArrayList;

class BinarySearch{
//Receives the list as the first argument, and the number to search
// for as the second argument.
public static boolean binarySearch(Object list[], Object target) {
    int listLen = list.length;
    int min = 0;
    int max = list.length - 1;
    //execute the binary search
    while (true) {
        int guess = (min + max / 2);
        if(target.equals(list[guess])) return true;

        if(list < target) {       //What to do here?
            //do some stuff

        ...  

我甚至不确定使用Object是最好的方法。

3 个答案:

答案 0 :(得分:0)

你不应该使用Object,你需要使用泛型类或方法 - 在我的例子中,我使用第二个,因为你的方法是静态的:

public class BinarySearch
{
    public static <T> boolean Run(T[] list, T target)
    {
    }
}

如果您需要比较值,可以使用Comparable<T>界面和compareTo方法,

  

将此对象与指定的订单对象进行比较。返回为负整数,零或正整数,因为此对象小于,等于或大于指定的对象。

让我们T延长Comparable<T>,并使用compareTo方法:

public class BinarySearch
{
  public static <T extends Comparable<T>> boolean Run(T[] list, T target)
  {
    int listLen = list.length;
    int min = 0;
    int max = list.length - 1;

    while (true) {
        int guess = (min + max / 2);
        if (target.equals(list[guess])) return true;

        if (list[guess].compareTo(target) < 0) { 
            // list[guess] is less than target
        } else {
            // list[guess] is larget than target
        }
    }
}

由于大多数Java类扩展Comparable,现在,您可以这样做:

Integer[] ints = { 1, 2, 3, 4, 5, 6, 7, 8, 10, 25, 30, 50, 100 };
System.out.println(BinarySearch.Run(ints, 25));
// recognized as: System.out.println(BinarySearch.<Integer>Run(ints, 25));

String[] strings = {"a", "b", "c", "d", "e"};
System.out.println(BinarySearch.Run(strings, "c"));
// recognized as: System.out.println(BinarySearch.<String>Run(strings, "c"));

如果BinarySearch扩展Comparable<>接口,您也可以使用TOTAL_KEY中的任何自定义类。

答案 1 :(得分:0)

为输入参数使用泛型类型,输入参数也包括Comparator,以便用户可以完全控制如何比较传入的任何类型的输入。

签名看起来像

public static <T> int binarySearch(
    T[] list, T target, java.util.Comparator<? super T> comparator) 

这比使对象实现Comparable更好,因为对象可能必须在不同情况下以不同方式排序。如果您使用Comparable,那么您只会使用您要比较的内容实现的方式,但是对于使用Comparable的搜索,您可以为输入列表排序的每种不同方式传入不同的比较器。

您的比较变为

int compareResult = comparator.compare(target, list[guess]);

其中结果为0表示2个对象相等,否定结果表示第一个参数小于第二个参数,而正结果表示第一个参数大于第二个参数。

检查您如何计算中点,由于运算符优先级的工作原理,您的代码被破坏了。如果您不小心,也可能会遇到大数组的问题(大于Integer.MAX_VALUE的一半)。

答案 2 :(得分:0)

我们可以使用java collections api中的Collections.binarySearch(...)方法,除非我遗漏了什么。

相关问题