欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

第50节:Java的当中的泛型

程序员文章站 2023-01-19 10:52:44
Java当中的泛型 01 这就存在一个问题,如果集合存储元素时,而且存储对象有很多,而且对象类型不相同,就很容易导致隐患。 在 中该文件 在编译的时候不会出现错误是因为该存储的是 的任何类型的对象,所以不会出现错误,编译通过了。编译后为 到运行。 如果要解决问题,可以把问题提前到编译的时候去解决,让 ......

第50节:Java的当中的泛型

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;
 }
}
// object
class 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 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
类 collections
java.lang.object
 -> java.util.collections
public class collections
extends object
public class collectionsdemo{
 // 集合框架中的操作集合对象的工具类,静态的方法
 collection<string> c = new arraylist<string>();
 c.add("dashu");
 c.add("dashucoding");
 string max = collections.max(c);
}
max
public 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;
 }
}
max
public 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);
 }
}

往后余生,唯独有你
简书作者:达叔小生
90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通
简书博客:

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞