Java Error(五)

错结果如图所示

代码无打错名字等问题,出错原因,初学容器,使用Collection 时,忘记引入包。

import java.util.*;
import java.util.*;

public class SetInterface {
    public static void main(String []args){
        Set s = new HashSet();
        s.add("hi");
        s.add("leaf");
        s.add(new Name("f1","l1"));
        s.add(new Integer(199));
        s.add(new Name("f2","l2"));
        s.add("hello");
        System.out.println(s);
    }
}

public static <T extends Comparable<? super T>> void insertOrder(T element,T[] a,int begin, int end) {    //element insert into a[begin] - a[end],construct order arr
        int index = end;
        while((index >= begin) && (element<a[index]) {
            a[index+1] = a[index];
            index --;
        }
        a[index+1] = element;
    }

出错原因: < 比较运算符只能对于基本数据类型进行操作,而上述代码中 ‘ < ’ 两侧为类型变量(非基本数据类型) 进行比较时,采用compareTo().通过返回值来判断大小。  

p.s. a.compareTo(b)    result >0  =>  a > b  result == 0  =>  a == b  result  < 0   =>   a < b

public static <T extends Comparable<? super T>> void insertOrder(T element,T[] a,int begin, int end) {    //element insert into a[begin] - a[end],construct order arr
        int index = end;
        while((index >= begin) && (element.compareTo(a[index])<0)) {
            a[index+1] = a[index];
            index --;
        }
        a[index+1] = element;
    }

上述为修改后结果,无误。

原文地址:https://www.cnblogs.com/leafh/p/8727994.html