Java set the lower limit wildcard

One o'clock eye

1 introduction

Java set frame TreeSet <E> a constructor which uses the lower limit set wildcard syntax, the syntax is as follows:

TreeSet(Comparator<? super E> c)

Two actual - set data copy

Code 1

import java.util.*;

public class MyUtils
{
   // 下面dest集合元素类型必须与src集合元素类型相同,或是其父类
   public static <T> T copy(Collection<? super T> dest
         , Collection<T> src)
   {
      T last = null;
      for (T ele  : src)
      {
         last = ele;
         dest.add(ele);
      }
      return last;
   }
   public static void main(String[] args)
   {
      List<Number> ln = new ArrayList<>();
      List<Integer> li = new ArrayList<>();
      li.add(5);
      li.add(9);
      li.add(7);
      // 此处可准确的知道最后一个被复制的元素是Integer类型
      // 与src集合元素的类型相同
      Integer last = copy(ln , li);    // ①
      System.out.println(ln);
   }
}

2 runs

[5, 9, 7]

Three combat - Sort application

Code 1

import java.util.*;

public class TreeSetTest {
    public static void main( String[] args ) {
        // Comparator的实际类型是TreeSet的元素类型的父类,满足要求
        TreeSet<Integer> ts1 = new TreeSet<>(
                new Comparator<Object>() {
                    public int compare( Object first, Object second ) {
                        return (Integer) first > (Integer) second ? 1 : -1;  // 返回-1时first排在前面,返回1时候second排在前面
                        // return -1;  // 返回-1时,second排在前面
                    }
                });
        ts1.add(1);
        ts1.add(2);
        // Comparator的实际类型是TreeSet元素的类型,满足要求
        TreeSet<String> ts2 = new TreeSet<>(
                new Comparator<String>() {
                    public int compare( String first, String second ) {
                        return first.length() > second.length() ? -1
                                : first.length() < second.length() ? 1 : 0;
                    }
                });
        ts2.add("wa");
        ts2.add("hello");


        System.out.println(ts1);
        System.out.println(ts2);
    }
}

2 runs

[1, 2]

[Hello, wa]

 

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/94768112