GVKun编程网logo

字符串类compareTo()方法返回什么(字符串的返回值类型)

16

对于字符串类compareTo感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解方法返回什么,并且为您提供关于Collection类的sort()方法如何调用Comparable的compar

对于字符串类compareTo感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解方法返回什么,并且为您提供关于Collection类的sort()方法如何调用Comparable的compareTo()?、comparable的compareTo( )方法 日常、compareTo () 方法返回值 String java、compareTo冒泡比较时间字符串的宝贵知识。

本文目录一览:

字符串类compareTo()方法返回什么(字符串的返回值类型)

字符串类compareTo()方法返回什么(字符串的返回值类型)

在oracles
网站上的Java
API中:“
compareTo返回:”如果参数字符串等于此字符串,则值为0;否则为0。如果此字符串在字典上小于字符串参数,则小于0的值;如果该字符串在字典上大于字符串参数,则该值大于0。

这是一个if语句:

String a = "abd";String b = "abc";if(a.compareTo(b) >= 1)

由于字符串a在字典上较大,因此返回true。

我的问题是,compareTo总是返回0、1或-1吗?还是返回字符串大于或小于字符串参数的实际 数量

因此,在上述if语句中,由于“ abd”比“ abc”大1,是否返回1?

答案1

小编典典

就您而言,没有告诉您compareTo返回值的大小是多少。实际上,大多数compareTo实现都将返回-1、0或1,但是合同明确规定了正数或负数,因此您应该相应地编写代码(例如,使用intcompare = a.compareTo(b); if(compare > 0) {...} else...)。

Collection类的sort()方法如何调用Comparable的compareTo()?

Collection类的sort()方法如何调用Comparable的compareTo()?

假设我要对Employee对象列表进行排序:

Employee emp1 = new Employee("Abhijit",10);
Employee emp2 = new Employee("Aniket",5);
Employee emp3 = new Employee("Chirag",15);

List<Employee> employees = new ArrayList<Employee>();
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);
Collections.sort(employees);
System.out.println("sorted List is: "+employees);

而且我的Employee类实现了Comparable,因此必须重写该compareTo()方法。
而且我必须在该compareTo()方法中编写排序逻辑。

class Employee implements Comparable<Employee>
{
    String name;
    int empId;
    public Employee(String name,int empId)
    {
        this.name= name;
        this.empId = empId;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getEmpId()
    {
        return empId;
    }
    public void setEmpId(int empId)
    {
        this.empId = empId;
    }
    @Override
    public int compareTo(Employee e)
    {
        // TODO Auto-generated method stub
        return this.empId > e.empId ? 1 : (this.empId < e.empId ? -1 : 0);
        //return 0;
    }
    @Override
    public String toString()
    {
        return String.valueOf(empId);
    }
}

内部如何sort()调用该compareTo()方法?

comparable的compareTo( )方法 日常

comparable的compareTo( )方法 日常

项目过程中遇到 类的排序 可以用这个类实现Comparable接口 ,重写comparaeTo方法来对这个类进行排序

在这个方法中 如果返回-1,则当前对象排在前面,如果返回1 ,则当前对象排在后面 ,返回0 .则相等

多的不说 直接上代码

实体类 :Student

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @authot Administrator
* @create 2018-05-20 13:43
*/
public class Student implements Comparable<Student>{
private Integer number;
private Double money;
private Date createdate;

public Student (Integer number,Double money,Date createdate) {
this.number = number;
this.money = money;
this.createdate = createdate;
}

public Integer getNumber() {
return number;
}

public Student setNumber(Integer number) {
this.number = number;
return this;
}

public Double getMoney() {
return money;
}

public Student setMoney(Double money) {
this.money = money;
return this;
}

public Date getCreatedate() {
return createdate;
}

public Student setCreatedate(Date createdate) {
this.createdate = createdate;
return this;
}

@Override
public String toString() {
return "number:"+number+";money:"+money+";createdate:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createdate);
}


@Override
public int compareTo(Student o) {
if (this.number > o.number) {
return -1;
}else if (this.number < o.number) {
return 1;
}else{
if (this.money > o.money) {
return 1;
}else if (this.money < o.money) {
return -1;
}else {
return this.createdate.compareTo(o.createdate);
}
}

}
}

 里面三个字段 ,数量,总额,和创建时间 先比较数量 再比较总额 ,最后比较时间,一般到时间维度也就比较出来了

在比较时间的维度 的时候直接使用compareTo方法 因为在日期类中已经对compareTo方法做了重写 所以可以直接比较

测试类:

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class Main {

public static void main(String[] args) throws Exception{
List<Student> students = new ArrayList<Student>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
students.add(new Student(1,400.0,format.parse("2018-05-20 13:01:02")));
students.add(new Student(2,300.0,format.parse("2018-05-20 13:20:02")));
students.add(new Student(3,200.0,format.parse("2018-05-20 13:14:02")));
students.add(new Student(4,100.0,format.parse("2018-05-20 13:16:02")));
students.add(new Student(5,500.0,format.parse("2018-05-20 13:08:02")));
students.add(new Student(5,500.0,format.parse("2018-05-20 13:08:03")));
students.add(new Student(3,500.0,format.parse("2018-05-20 13:08:02")));
students.add(new Student(1,600.0,format.parse("2018-05-20 13:08:02")));

Collections.sort(students);

for (Student student : students) {
System.out.println(student);
}
}
}

运行结果如下:

number:5;money:500.0;createdate:2018-05-20 13:08:02
number:5;money:500.0;createdate:2018-05-20 13:08:03
number:4;money:100.0;createdate:2018-05-20 13:16:02
number:3;money:200.0;createdate:2018-05-20 13:14:02
number:3;money:500.0;createdate:2018-05-20 13:08:02
number:2;money:300.0;createdate:2018-05-20 13:20:02
number:1;money:400.0;createdate:2018-05-20 13:01:02
number:1;money:600.0;createdate:2018-05-20 13:08:02

 

第一次写博客希望可以对你得到帮助,多多指教

 

compareTo () 方法返回值 String java

compareTo () 方法返回值 String java

compareTo () 方法返回值 String java 博客分类: java
前言:今天浏览网页时看见有人对 String 类的 compareTo () 方法的返回值感到疑惑不解,所以我写了这篇文章,希望能帮助这些有疑惑的人. 

compareTo () 的返回值是整型,它是先比较对应字符的大小 (ASCII 码顺序), 如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方全比较完,这时就比较字符的长度. 


例: 
String s1 = "abc"; 
String s2 = "abcd"; 
String s3 = "abcdfg"; 
String s4 = "1bcdfg"; 
String s5 = "cdfg"; 
System.out.println (s1.compareTo (s2) ); //-1 (前面相等,s1 长度小 1) 
System.out.println (s1.compareTo (s3) ); //-3 (前面相等,s1 长度小 3) 
System.out.println (s1.compareTo (s4) ); // 48 ("a" 的 ASCII 码是 97,"1" 的的 ASCII 码是 49, 所以返回 48) 
System.out.println (s1.compareTo (s5) ); //-2 ("a" 的 ASCII 码是 97,"c" 的 ASCII 码是 99, 所以返回 - 2)
 
 

/**
     * Compares two strings lexicographically.
     * The comparison is based on the Unicode value of each character in
     * the strings. The character sequence represented by this
     * <code>String</code> object is compared lexicographically to the
     * character sequence represented by the argument string. The result is
     * a negative integer if this <code>String</code> object
     * lexicographically precedes the argument string. The result is a
     * positive integer if this <code>String</code> object lexicographically
     * follows the argument string. The result is zero if the strings
     * are equal; <code>compareTo</code> returns <code>0</code> exactly when
     * the {@link #equals(Object)} method would return <code>true</code>.
     * <p>
     * This is the definition of lexicographic ordering. If two strings are
     * different, then either they have different characters at some index
     * that is a valid index for both strings, or their lengths are different,
     * or both. If they have different characters at one or more index
     * positions, let <i>k</i> be the smallest such index; then the string
     * whose character at position <i>k</i> has the smaller value, as
     * determined by using the &lt; operator, lexicographically precedes the
     * other string. In this case, <code>compareTo</code> returns the
     * difference of the two character values at position <code>k</code> in
     * the two string -- that is, the value:
     * <blockquote><pre>
     * this.charAt(k)-anotherString.charAt(k)
     * </pre></blockquote>
     * If there is no index position at which they differ, then the shorter
     * string lexicographically precedes the longer string. In this case,
     * <code>compareTo</code> returns the difference of the lengths of the
     * strings -- that is, the value:
     * <blockquote><pre>
     * this.length()-anotherString.length()
     * </pre></blockquote>
     *
     * @param   anotherString   the <code>String</code> to be compared.
     * @return  the value <code>0</code> if the argument string is equal to
     *          this string; a value less than <code>0</code> if this string
     *          is lexicographically less than the string argument; and a
     *          value greater than <code>0</code> if this string is
     *          lexicographically greater than the string argument.
     */
    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }
 

compareTo冒泡比较时间字符串

compareTo冒泡比较时间字符串

public static void main(String[] args) {
        List<String> dates = new ArrayList<String>();
        dates.add("2018-06-01");
        dates.add("2018-05-23");
        dates.add("2018-05-06");
        dates.add("2018-01-06");
        dates.add("2018-05-20");
        Map<String, String> data = new HashMap<String, String>();
        data.put("2018-06-01", "lws");
        data.put("2018-05-23", "sss");
        data.put("2018-05-06", "www");
        data.put("2018-01-06", "sl1");
        data.put("2018-05-20", "lll");
        
        String[] array =new String[dates.size()];
        dates.toArray(array);
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length- i - 1; j++) {
                if (array[j].compareTo(array[j + 1]) > 0) {
                    String temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        System.out.println(data.get(array[0]));
}

 

今天关于字符串类compareTo方法返回什么的讲解已经结束,谢谢您的阅读,如果想了解更多关于Collection类的sort()方法如何调用Comparable的compareTo()?、comparable的compareTo( )方法 日常、compareTo () 方法返回值 String java、compareTo冒泡比较时间字符串的相关知识,请在本站搜索。

本文标签: