继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

第50节:Java当中的泛型

慕神8447489
关注TA
已关注
手记 1134
粉丝 172
获赞 955

webp

标题图

Java当中的泛型

01

import java.util.ArrayList;import java.util.List;public class Demo{
 public static void main(String[] args){  // 创建list集合
  List list = new ArrayList(); // 特性为长度可变,可以存储对象(对象可以是任意的)
  list.add("abcdefg"); // 为对象
  list.add(1); // 为对象
  // 循环取出对象
  for(Iterator it = list.iterator(); it.hasNext(); ){
   Object object = (Object) it.next();
   System.out.println(object.toString());
  }  // 打印字符串的长度
  // 因为字符串的长度是字符串的特有方法,所以需要进行转型
  String str = (String) it.next();
  System.out.println(str.length());
 }
}
String str = (String) it.next();
System.out.println(str.length());// 导致错误java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String// 因为存储的对象有Integer类型不能转换为String类型

这就存在一个问题,如果集合存储元素时,而且存储对象有很多,而且对象类型不相同,就很容易导致隐患。

Java中该文件xxx.java在编译的时候不会出现错误是因为该存储的是Object的任何类型的对象,所以不会出现错误,编译通过了。编译后为xxx.class到运行。

如果要解决问题,可以把问题提前到编译的时候去解决,让集合更加安全,但是如何解决呢?

在集合中存储的类型是可以任意的,所以会导致留下隐患,我们认识的数组在存储的时候就不会出现这种错误,因为它一开始就明确了存储的内存类型,一旦不是它要存储的类型就会编译不过去导致出错。

在集合中,我们可以一开始就明确要在容器中存储的什么类型的元素,跟数组一样就好了啊!那就不会出现ClassCastException的问题啦!

那么如何创建集合,规定存储定义的类型呢?这就需要有泛型了,有了泛型,就可以保证安全机制了,可以将运行时期转移到编译时期,泛型的出现就是为了给编译使用的,泛型的出现就可以不用强转了。

List<String> list = new ArrayList<String>();

泛型类运用

一直以来,你看到的<E>,就是所谓的泛型表达

java.util
接口 Collection<E>

泛型案例

public class Demo{
 public static void main(String[] args){  // 添加泛型
  Set<String> set = new TreeSet<String>();  // 添加元素
  set.add("a");  set.add("ab");  for(Iterator<String> it = set.iterator(); it.hasNext();){  // 不用转换了
  String str = it.next();
  System.out.println(str);
 }
 }
}

进行比较长度:

Set<String> set = new TreeSet<String>(new Comperator>(){ @Override
 public int compare(String o1, String o2){  int temp = o1.length() - o2.length();  return temp == 0 ? o1.compareTo(o2) : temp;
 }
}

泛型类 可能导致ClassCastException

// 简书作者:达叔小生public static void main(String[] args){
 Demo d = new Demo();
 d.setObject(23); String s = (String) d.getObject();
 System.out.println(s);
}
class Demo{
 private String str; public String getStr(){  return str;
 } public void setStr(String str){  this.str = str;
 }
}// Objectclass Demo{
 private Object object; public Object getObject(){  return object;
 } public void setObject(Object object){  this.object = object;
 }
}

02

JDK1.5开始的新技术

// 泛型类-泛型定义在类上class Demo(D){ private D object; public D getObject(){  return object;
 } public void setObject(D object){  this.object = object;
 }
}
Demo<String> d = new Demo<String>();
d.setObject("abc"); // 只能传递String类型String s = d.getObject();
System.out.println(s);

泛型方法的使用

// 简书作者:达叔小生class Demo<D>{
 public <D> void show(D d){  // 泛型方法
  System.out.println("show"+d);
 } public static<E> void print(E e){  // 方法为静态,使用泛型,需要定义在方法上
  System.out.println("print"+d);
 }
}
public static void mian(String[] args){
 Demo<String> demo = new Demo<String>();
 demo.show("abc");
 demo.print("abc");
}

泛型接口

// 简书作者:达叔小生interface Inter<E>{ void show(E e);
}
class InterDemo implements Inter<String>{
 ...
}class InterDemo<T> implements Inter<T>{ public void show(T t){
  ...
 }
}

泛型通配符

public class Demo{
 public static main(String[] args){
  List<Student> list = new ArrayList<Student>();  list.add(new Student("dashu",20));  list.add(new Student("dashu1",21));  list.add(new Student("dashu2",22));  for(Iterator<Student> it = list.iterator(); it.hasNext();){
  System.out.println(it.next());
  } // 打印
 private static void print(Collection<Student> coll){   for(Iterator<Student> it = coll.iterator(); it.hasNext();){
   System.out.println(it.next());
  } // 打印
 private static void printList(Collection<?> coll){  for(Iterator<?> it = coll.iterator(); it.hasNext();){
   System.out.println(it.next().toString());
 } // 打印
 private static void printList(Collection<? extends Person> coll){  for(Iterator<? extends Person> it = coll.iterator(); it.hasNext();){
   Person p = it.next();
   System.out.println(p.getName());
  }
 }
 }
 }
}

? extends E:接收E类型或者E的子类型
? super E:接收E类型或者E的父类型

// 简书作者:达叔小生public class Person{ // 定义属性
 private String name; private int age; // 定义构造方法
 public Person(){  super();
 } // 有参的构造方法
 public Person(String name, int age){  super();  this.name = name;  this.age = age;
 } public String getName(){  return name;
 } public void setName(String name){  this.name = name;
 } public int getAge(){  return age;
 } public void setAge(int age){  this.age = age;
 } // toString
 @Override
 public String toString(){  return "Person [ name=" + name + ",age=" + age + "]";
 }
}
public class Student extends Person{ public Student(){  super();
 } public Student(String name, int age){  super(name,age;
 }@Override
 public String toString(){  return "Student [getName()=" + getName() + ",getAge()=" + getAge() + "]";
 }
}
public class Worker extends Person{ public Worker(){  super();
 } public Worker(String name, int age){  super(name, age);
 } @Override
 public String toString(){  return "Worker [name =" + getName() + ", age =" + getAge() + "]";
 }
}

通配符的体现

Collection<String> c1 = new ArrayList<String>();
c1.add("dashu");
Collection<String> c2 = new ArrayList<String>();
c2.add("dashucoding");
boolean b = c1.containsAll(c2);// boolean containsAll(Collection<?> c);System.out.println("b="+b);// 结果为 false

内源码

// 简书作者:达叔小生public boolean containsAll(Collection<?> c){ for(Object o : c){  if(!contains(o)){   return false;
  }  return true;
 }
}
java.util类 TreeSet<E>java.lang.Object
 -> java.util.AbstractCollection<E>  -> java.util.AbstractSet<E>   -> java.util.TreeSet<E>
参数E:为此set要维护的元素类型
public class TreeSet<E>extends AbstractSet<E>implements NavigableSet<E>,Cloneable,Serializable

TreeSet的构造方法

方法说明
TreeSet()构造方法,更具元素自然排序
TreeSet(Collection<? extends E> c)构造一个包含collection元素的新TreeSet,按照其元素自然顺序进行排序
TreeSet(Comparator<? super E> comparator)构造一个新的空TreeSet,它根据指定比较进行排序
TreeSet(Sorted<E> s)构造一个有序的set,具有相同的映射关系与相同排序的TreeSet
public class Person implements Comparable<Person> { // 定义属性
 private String name; private int age; // 定义构造方法
 public Person(){  super();
 } // 有参的构造方法
 public Person(String name, int age){  super();  this.name = name;  this.age = age;
 } public String getName(){  return name;
 } public void setName(String name){  this.name = name;
 } public int getAge(){  return age;
 } public void setAge(int age){  this.age = age;
 } // toString
 @Override
 public String toString(){  return "Person [ name=" + name + ",age=" + age + "]";
 } @Override
 public int compareTo(Person o){  int temp = this.age - o.age;  return temp == 0?this.name.compareTo(o.name) : temp;  return 0;
 }
}
Collection<Person> c = new ArrayList<Person>();
c.add(new Person("dashu",12));
c.add(new Person("dashucoding",13));

TreeSet<Person> ts = new TreeSet<Person>(c);
ts.add(new Person("dashuxiaosheng",14));for(Iterator<Person> it = ts.iterator(); it.hasNext();){
 Person person = it.next(();
 System.out.println(person);
}
// 简书作者:达叔小生TreeSet<Student> ts = new TreeSet<Student>(new ComparetoName() );
ts.add(new Student("dashu",12));
ts.add(new Student("dashucoding",13));for(Iterator<Student> it = ts.iterator(); it.hasNext();){
 Student student = it.next();
 System.out.println(student);
}
class ComparetoName implements Comparator<Student>{ @Override
 public int compare(Student  o1, Student o2){  int temp = o1.getName().compareTo(o2.getName());  return temp == 0 ? o1.getAge() - o2.getAge() : temp;
 }
}
ArrayList<Dog> a = new ArrayList<Dog>(); // 可以ArrayList<Object> a = new ArrayList<String>(); // 不可以

泛型的特点

public class Demo{
 public static void main(String[] args){  // 获取集合中的最大值元素
  Collection c = new ArrayList();
  c.add(new Student("da",12));
  c.add(new Student("dashu",13));
  c.ass(new Student("dashucoding",14));
  Student stu = getMax(c);
  System.out.println(stu);
 } public static Student getMax(collection<Student> c){
   Iterator<Student> it = c.iterator();
   Student max = it.next();   while(it.hasNext()){
    Student temp = it.next();    if(temp.compareTo(max) > 0){
     max = temp;
    }
   }   return max;
 }
}
// 简书作者:达叔小生public static <T extends Comparable<? super T>> T getMax(Collection<? extends T> c){
 Iterator<? extends T> it = c.iterator();
 T max = it.next();  while(it.haxNext()){
   T temp = it.next();    if(temp.compareTo(max)>0){
     max = temp;
    }
  }
}

Collections工具类

java.util类 Collectionsjava.lang.Object
 -> java.util.Collections
public class Collectionsextends Object
public class CollectionsDemo{ // 集合框架中的操作集合对象的工具类,静态的方法
 Collection<String> c = new ArrayList<String>();
 c.add("dashu");
 c.add("dashucoding"); String max = Collections.max(c);
}
maxpublic static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

源码

// 简书作者:达叔小生public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll){
 Iterator<? extends T> i = coll.iterator();
 T candidate = i.next(); while(i.hasNext()){
  T next = i.next();  if(next.compareTo(candidate) > 0){
   candidate = next;
  }  return candidate;
 }
}
maxpublic static <T> T max (Collection<? extends T> coll,Comparator<? super T> comp)// 可以根据比较器产生顺序
 Collection<String> c = new ArrayList<String>();
 c.add("dashu");
 c.add("dashucoding"); String max = Collections.max(c, new Comparator<String>(){
@Override
 public int compare(String o1, String o2){
  int temp = o1.length() - o2.length();  return temp == 0?o1.compareTo(o2) : temp;
 }
});

源码

public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp){ if(comp == null){  return (T)max((Collection<SelfComparable>)(Collection) coll);
 Iterator<? extends T> i = coll.iterator();
 T candidate = i.next(); while(i.hasNext()){
  T next = i.next();  if(comp.compare(next, candidate) > 0)
   candidate = next;
 } return candidate;
 }
}

排序

List<String> llist = new ArrayList<String>();list.add("a");list.add("add");list.add("sl");list.add("dljf");
Collections.sort(list);

长度排序

public class ComparatorLength implements Comparator<String>{ @Override
 public int compare(String o1, String o2){  int temp = o1.length() - o2.length();  return temp == 0 ? o1.compareTo(o2) : temp;
 }
}

集合和数组

public class ArraysDemo{
 public static void main(String[] args){ int[] arr = {23,434,575};
 System.out.println(Arrays.toString(arr));
 
 String[] strs = {"dashu","da","shu"};
 
 List<String> list = Arrays.asList(strs);
 System.out.println(list);
 }
}



作者:达叔小生
链接:https://www.jianshu.com/p/e73038d21c3d


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP