zoukankan      html  css  js  c++  java
  • 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;
        }

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

  • 相关阅读:
    java web spring challenge01
    eclipse的一个小失误
    创建线程的方式三:实现Callable接口。 --- JDK 5.0新增
    线程通信的应用:经典例题:生产者/消费者问题
    8.5 练习
    8.4 练习1
    LockTest.java
    DeadLock.java
    线程死锁
    使用同步机制将单例模式中的懒汉式改写为线程安全的
  • 原文地址:https://www.cnblogs.com/leafh/p/8727994.html
Copyright © 2011-2022 走看看