自定义泛型集合,接口
生活随笔
收集整理的這篇文章主要介紹了
自定义泛型集合,接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自定義泛型集合
package C12_21;public class abstractList {public static void main(String[] args) {stu<String> stus = new stu<String>();stus.setS("hello");System.out.println(stus.getS());// 靈活, 可以傳入任意數據類型。 將運行錯誤轉變為編譯錯誤。stus.show("hhh");}}// 從泛型集合, 可以 學到自定義集合類。 class stu<S, V> {private S s;private V v;public void setS(S s) {this.s = s;}public S getS() {return s;}public void setV(v v) {this.v = v;}public V getV(V v) {return v;}// 自定義泛型方法// 語法:自定義泛型方法 修飾符 + <類型> + 返回值 + 方法名(參數) { 方法體 } public <T> T show(T t) {System.out.println(t);return t;}// 靜態泛型方法 類型J和 S,不能一樣public static <J> void setObj(J j) {System.out.println(j);}// 下面兩個方法是易錯的。public static<S> void setObj(S s) { // 無法解析str或str不是字段// System.out.println(s.str);// 正確System.out.println(s); }// 錯誤, 不能對非靜態類型S進行靜態引用/*public static void setObj<S s> {System.out.println(s);}*/ }Result
hello hhh自定義泛型接口, Comparable
// 泛型接口A,可以支持多種類型讓子類實現。 interface A<O> { }class B implements A<String> {public void show(String str) {System.out.println(str);} }Demo
- Comparable 比較接口就是泛型接口應用的一個經典例子。
- 先看看基本數據類型的compareTo方法
測試
Student[] stus = new Student[3];stus[0] = new Student("abc", 12);stus[1] = new Student("jb", 18);stus[2] = new Student("abcc", 2);for (Student stu : stus) {System.out.print(stu + "\t"); }// Comparable 接口, 用arrays的sort排序。Arrays.sort(stus);System.out.println("\n" + "排序后");for (Student stu : stus) {System.out.print(stu + "\t");}結果如下
Student [name=abc, age=12] Student [name=jb, age=18] Student [name=abcc, age=2] 排序后 Student [name=abcc, age=2] Student [name=abc, age=12] Student [name=jb, age=18]總結
以上是生活随笔為你收集整理的自定义泛型集合,接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python库pygame下载教程
- 下一篇: 如何学习streamdecoder类_2