如何比较两个字符串?

时间:2019-04-17 19:10:00

标签: java comparable

我正在尝试使用Java的类似内容来理解老师从本练习中得到的东西。

我不确定我需要做什么。有人可以给我一个很好的开端吗?

public class BookTag implements Comparable {

    private String left;
    private int mid;
    private String right;

    public BookTag(String left, int mid, String right) {
        check(left, mid, right);
        this.left = left.toUpperCase();
        this.mid = mid;
        this.right = right.toUpperCase();
    }

    @Override
    public int compareTo(Object arg) {

        /*
         * Booktags are sorted as follows: - first go booktags with lowest left
         * attribute. If left attributes cannot discriminate... - ... first go booktags
         * with the lowest mid attribute. If mid cannot discriminate... - ... first go
         * booktags with HIGHEST right attribute.
         */

        /* COMPLETE */
        BookTag tag = (BookTag) arg; 

        return this.left.compareTo(tag.compareTo(left));


    }
}

在这里我需要比较哪些价值观之王?

2 个答案:

答案 0 :(得分:1)

无法像自然类型那样自然地比较对象,因此您必须自己提供一些排序。一种实现方法是实现Comparable<T>接口。

public class BookTag implements Comparable<BookTag> {

     //compares this tag with another: 0 indicates equality, 1 means this is  
     //bigger, -1 means the other is bigger
     public int compareTo(BookTag other) { 

          int c = this.left.compareTo(other.left); //string implements this
          if(c != 0) { 
                return -c; //if the other's left is "smaller", this object is "bigger"
          }

          c = this.mid - other.mid;
          if(c != 0) { 
                return -c; //if the other's mid is "smaller", this object is "bigger"
          }

           c = this.right.compareTo(other.right);
           if(c != 0) { 
                return c; //if the other's right is "bigger", this object is "bigger"
          }

          return 0; //if we get here, then all values are equal, and so are the objects
     }   
}

为了简化一些代码,我实现了Comparable<BookTag>而不是原始的Comparable

答案 1 :(得分:0)

BookTag other = ((BookTag)o); // cast it
int leftcompare = this.left.compareTo(other.getLeft());
int midCompare = this.mid - other.getMid();
// careful with the right compare as the highest goes first
int rightCompare = this.right.compareTo(other.getRight());


// if , then, else statement to fill your teacher's requirements
// negative number means that this book tag is higher on the compare list
// 0 means cannot discriminate (move to the next field left -> mid -> right
// positive number means the other BookTag is higher on the list

我不知道这一点,但也许您可以权重这些值,而不是if-then-else。玩得开心:)

相关问题