Java泛型
2021-04-08 13:25
标签:str col -- src test ima 泛型 zip etag Java泛型 标签:str col -- src test ima 泛型 zip etag 原文地址:https://www.cnblogs.com/yzg-14/p/13378446.htmlpackage com.qf.demo01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.zip.CRC32;
public class Test1Generics {
public static void main(String[] args) {
//1.不适用泛型
Collection c1 = new ArrayList();
c1.add("abc");//String-->Object
c1.add(100);//int->Integer-->Object
//for-each遍历
for(Object obj:c1){
if(obj instanceof String){
String s = (String) obj;//自己手动的向下转型
System.out.println(s);
}
}
System.out.println("----------------------");
//2.使用泛型
Collection
package com.qf.demo01;
import java.util.ArrayList;
import java.util.Collection;
class Person{
private String name;
private int age;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
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;
}
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
public class Test2Generics {
public static void main(String[] args) {
//课间练习:创建一个集合容器,声明泛型为Person,存储3个人的对象,然后使用for-each遍历输出。
Collection
上一篇:Java 接口