如何比较两个字符串?

How to compare two string?

我正在尝试使用 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));


    }
}

我需要在这里比较什么价值观?

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。玩得开心:)

对象不能像原始类型那样自然地进行比较,所以你必须自己提供一些排序。一种方法是实现 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 以获得更简单的代码。