泛型相关用法(day3)

一、instanceof 用法总结.
instanceof属于java关键字之一,instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例,用法为:boolean result = obj instanceof Class

二、泛型:常见的字母及分别对应含义?
E - Element (在集合中使用,因为集合中存放的是元素)
T - Type(Java 类)
K - Key(键)
V - Value(值)

三、泛型的优点是安全和省心,请用代码说明。
将对象类型作为参数,制定到其它类和方法上,从而保证类型转换的安全性和稳定性,本质是参数化类型
Map<String, String> countries = new HashMap<String, String>();
countries.put(“China”, “中国”);
countries.put(“USA”, “美国”);
countries.put(“Japan”, “日本”);
countries.put(“France”, “法国”);
Set<Map.Entry<String, String>> set = countries.entrySet(); //获取Map中的键值对
for (Map.Entry<String, String> me : set) {
String key = me.getKey(); //获取出来键值对中的键
String value = me.getValue(); //获取出来键值对中的值
System.out.println(key + “–” + value);
}

四、泛型接口注意事项是什么?
1.接口上自定义泛型的具体数据类型是在实现接口的时候指定的;
2.在接口上自定义的泛型,如果在实现接口的时候,没有指定具体的数据类型,那么默认为Object类型;

五、泛型方法注意事项是什么?
1.使用泛型可以解决类型转换的问题:在编译器发现问题,而不是运行期才发现
2.泛型只能是引用类型,不能是基本类型
3.方法中如果有泛型,那么传入的参数类型必须和方法中声明的类型完全一致
如果希望方法中的泛型可以接收任意类型那么不能使用object,可以使用通配符?(问号)
4.一个泛型类的参数可以是一般的引用类型的参数,也可以是一个泛型类
5.泛型类可以是继承泛型类
6.在泛型中不可以用泛型的变量加一个泛型的变量

六、泛型:(1)子类指定具体类型,(2)子类为泛型类,(3)子类为泛型类/父类不指定类型,(4)子类与父类同时不指定类型,以上4点请分别用代码举例。
package Col;
public class Test {
/**
* 泛型类继承规则:
* 要么同时擦除,要么子类大于等于父类类型
/
public abstract class Father {
T name;
public abstract void test(T name);
}
/

* 子类声明为具体类型(具体类型大于泛型)
* 属性类型为具体类型
* 方法同理
/
class Child1 extends Father{
public void test(Integer name) {
}
}
/
*
* 子类为泛型,类型在使用时确定(子类有两个,大于父类一个)*
/
class Child2<T,T1> extends Father{
public void test(T name) {
}
}
/
*
* 子类为泛型,父类不指定类型,使用Object替代(子类一个,父类没有
/
class Child3 extends Father{
public void test(Object name) {
}
}
/
*
* 子类与父类同时擦除,用Object替代
*/
class Child4 extends Father{
public void test(Object name) {
}
}
}

七、泛型接口,方法是以父类而定还是以子类而定?
1.属性类型
父类中,随父类而定
子类中,随子类定。
2.方法重写随父类而定

八、形参使用多态、返回类型使用多态 请分别代码举例。
1.形参使用多态
//父类:提取共性代码
//抽象类不能被实例化,实例化没有任何实际意义
public abstract class Pet {
private String name = “无名氏”; // 昵称,默认值是"无名氏"
private int health = 100; // 健康值,默认值是100,健康值在0-100之间,小于60为不健康
private int love = 0; // 亲密度,在0-100之间
public Pet(){
System.out.println(“父类无参构造方法”);
}
public Pet(String name){
this.name = name;
}
public Pet(String name,int health,int love){
//this(name); //this可调用本类的构造方法,且必须在第一行
this.name = name;
this.health = health;
this.love = love;
System.out.println(“父类带参构造方法”);
}
public void setHealth(int health){
if(health<0 || health>100){
System.out.println(“宠物的健康值只能在0-100之间!”);
this.health = 60;
return;
}
this.health = health;
}
public int getHealth(){
return this.health;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setLove(int love){
if(love<0 || love>100){
System.out.println(“宠物的亲密度只能在0-100之间!”);
this.love = 60;
return;
}
this.love = love;
}
public int getLove(){
return this.love;
}
/**
* 输出宠物的信息
*/
public void print() {
System.out.println(“宠物的自白:\n我的名字叫” + this.name +
“,健康值是” + this.health + “,和主人的亲密度是”
+ this.love );
}
//宠物生病后看病
//抽象方法所在的类必须定义为抽象类
//抽象类中一定要有抽象方法吗?不一定
//一个抽象类的抽象方法必须被子类(普通)实现
//除非其子类也是抽象类
public abstract void toHospital();
//宠物吃饭
public abstract void eat();
}

/**

  • 宠物狗狗类
    /
    public class Dog extends Pet {
    private String strain = “聪明的拉布拉多犬”; // 品种
    public Dog(){
    System.out.println(“子类狗狗的无参构造方法”);
    }
    public Dog(String name,int health,int love){
    super(name,health,love);
    System.out.println(“子类狗狗带三个参数的构造方法”);
    }
    public Dog(String name,int health,int love,String strain){
    /
    //通过super调用父类的构造方法,必须是第一行
    //super();
    super(name,health,love);*/
    this(name,health,love);
    this.strain = strain;
    System.out.println(“子类狗狗带4个参数的构造方法”);
    }
    public void setStrain(String strain){
    this.strain = strain;
    }
    public String getStrain(){
    return this.strain;
    }
    public void print() {
    //调用父类的非private方法print()
    super.print();
    System.out.println(“我是一只:”+this.strain );
    }
    //宠物生病后看病
    public void toHospital(){
    System.out.println(“打针、吃药”);
    this.setHealth(60);
    }
    //狗狗吃骨头
    public void eat(){
    if(this.getHealth()>=100){
    System.out.println(“狗狗”+this.getName()+“吃饱了,不需要喂食了!”);
    }else{
    //狗狗的健康值+3
    this.setHealth(this.getHealth()+3);
    System.out.println(“狗狗”+this.getName()+“吃饱了!健康值加3!”);
    }
    }
    //狗狗叼飞碟
    public void catchFly(){
    System.out.println(“狗狗叼飞碟!”);
    }
    }

/**

  • 宠物企鹅
    */
    public class Penguin extends Pet{
    private String sex = “Q仔”; // 性别
    public Penguin(){}
    public Penguin(String name,int health,int love,String sex){
    super(name,health,love);
    this.sex = sex;
    }
    public String getSex() {
    return sex;
    }
    public void setSex(String sex) {
    this.sex = sex;
    }
    public void print() {
    super.print();
    System.out.println(“我的性别是:”+this.sex );
    }
    //宠物生病后看病
    public void toHospital(){
    System.out.println(“吃药、疗养”);
    this.setHealth(60);
    }
    //企鹅吃鱼
    public void eat(){
    if(this.getHealth()>=100){
    System.out.println(“企鹅”+this.getName()+“吃饱了,不需要喂食了!”);
    }else{
    //企鹅的健康值+5
    this.setHealth(this.getHealth()+5);
    System.out.println(“企鹅”+this.getName()+“吃饱了!健康值加5!”);
    }
    }
    //企鹅在南极游泳
    public void swim(){
    System.out.println(“企鹅在南极游泳!”);
    }
    }
    //主人类
    public class Master {
    //为宠物看病:如果宠物健康值小于50,就要去宠物医院看病
    public void cure(Pet pet){
    if(pet.getHealth()<50){
    pet.toHospital();
    }
    }
    //为宠物喂食
    public void feed(Pet pet){
    pet.eat();
    }
    }
    import java.util.Scanner;
    public class TestPet {
    public static void main(String[] args) {
    Master master = new Master();
    Scanner input = new Scanner(System.in);
    System.out.println(“欢迎您来到宠物店!”);
    System.out.print(“请输入要领养宠物的名字:”);
    String name = input.next();
    System.out.print("请输入要领养宠物的类型:1、狗狗 2、企鹅 ");
    int typeNo = input.nextInt();
    switch(typeNo){
    case 1:
    //创建狗狗对象
    /Dog dog=new Dog();
    dog.setName(name);
    //狗狗其他属性的用户键盘录入和赋值请课下自行补充
    dog.setHealth(-1000);
    dog.setLove(-9);
    dog.setStrain(“吉娃娃”);
    dog.print();
    /
    //Pet pet = new Pet() 类名 对象名 = new 类名();
    //Person p = new Student();
    //Person p = new Teacher();
    //父类类型指向子类对象,向上转型
    Pet dog = new Dog(“多多”,30,89,“吉娃娃”);
    //使用向上转型无法调用子类独有的方法
    //可使用向下转型
    /Dog d = (Dog)dog;
    d.catchFly();
    /
    //向下转型,如果没有转化为真实的子类类型,此时会引发ClassCastException
    /Penguin p1 = (Penguin)dog;
    p1.swim();
    /
    //可使用instanceof进行类型判断
    if(dog instanceof Dog){
    Dog d = (Dog)dog;
    d.catchFly();
    }else if(dog instanceof Penguin){
    Penguin p = (Penguin)dog;
    p.swim();
    }
    /dog.print();
    System.out.println(“");
    //主人为狗狗看病
    master.cure(dog);
    //主人为狗狗喂食
    master.feed(dog);
    System.out.println("
    ”);
    dog.print();

    break;
    case 2:
    //接收用户键盘录入信息
    System.out.print(“请选择企鹅的性别:1、Q妹 2、Q仔”);
    int sexId = input.nextInt();
    String sex = (sexId==1)? “Q妹” :“Q仔”;
    System.out.print(“请输入企鹅的健康值:”);
    int health = input.nextInt();
    System.out.print(“请输入企鹅的亲密度:”);
    int love = input.nextInt();
    //创建企鹅对象,并为企鹅属性赋值
    /Penguin p=new Penguin();
    p.setHealth(health);
    p.setLove(love);
    p.setName(name);;
    p.setSex(sex);
    p.print();
    /
    Pet p = new Penguin(name,health,love,sex);
    if(p instanceof Dog){
    Dog d = (Dog)p;
    d.catchFly();
    }else if(p instanceof Penguin){
    Penguin penguin = (Penguin)p;
    penguin.swim();
    }
    /p.print()
    System.out.println(“");
    //主人为企鹅看病
    master.cure§;
    //主人为企鹅喂食
    master.feed§
    System.out.println("
    ”);
    p.print();
    /
    break;
    default:
    System.out.println(“暂时没有这个类型的宠物!”);
    break;
    }
    }
    }

2.返回值类型使用多态
//商品类
public abstract class Goods {
//打印输出商品价格
public abstract void printPrice();
}
//食品类
public class Foods extends Goods {
public void printPrice() {
System.out.println(“打印输出食品价格”);
}
}
//电视类
public class TVs extends Goods {
public void printPrice() {
System.out.println(“打印输出电视价格”);
}
}
//商品工厂,可以根据厂家需求生产不同的商品
public class Factory {
//生产商品:使用父类作为方法返回值类型
public Goods getGoods(String str){
if(str.equals(“food”)){
return new Foods();
}else{
return new TVs();
}
}
}
//测试商品生产及输出商品价格
public class Test {
public static void main(String[] args) {
Factory factory = new Factory();
Goods goods = factory.getGoods(“food”);
goods.printPrice();

	goods = factory.getGoods("tvs");
	goods.printPrice();
}

}
九、泛型有没有多态?
泛型没有多态

十、泛型的?问号: 只能声明在类型|方法上,不能声明类或者使用时,请用代码证明这句话的正确性.
public boolean addAll(Collection <? extends E > c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0 , elementData, size, numNew);
size += numNew;
return numNew != 0 ;
}

十一、泛型嵌套:由外到内拆分.请用代码解释这句话.
public class Bjsxt {
T stu;
public static void main(String[] args) {
//泛型的嵌套
Bjsxt<Student> room = new Bjsxt<Student>();
//从外到内拆分
room.stu = new Student();
Student stu1 = room.stu;
String score = stu1.score;
System.out.println(score);
}
}

十二、泛型有没有数组?
泛型没有数组

十三、用匿名内部类实现迭代器。
package Col;
import java.util.Iterator;
public class MyArrayList implements java.lang.Iterable{
private String[] elem = {“a”, “b”, “c”, “d”, “e”, “f”, “g”};
private int size = elem.length;
public Iterator iterator() {
return new Iterator() {
private int cursor = -1;
public boolean hasNext() {
return cursor + 1 < size;
}
public String next(){
cursor++;
return elem[cursor];
}
public void remove(){
}
};
}
public static void main(String[] args){
MyArrayList list=new MyArrayList();
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
it.remove();
}
it=list.iterator();
while (it.hasNext()){
System.out.println(it.hasNext());
}
System.out.println(“增强for,必须实现java.lang.Iterable接口,重写Iterable”);
for(String temp:list){
System.out.println(temp);
}
}
}

十四、用分拣思路统计字符串出现次数"this-is-my-first-dog-but-i-like-cat-and-cat-is-nice-and-dog-is-friendly-this-why-i-like-cat-more".
1.封装单词类
package Map;
public class Letter {
private String name;
private int count;
public Letter(String name, int count) {
super();
this.name = name;
this.count = count;
}
public Letter() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
2.用分拣思路统计字符串出现次数
import java.util.Set;
public class Demo01 {
public static void main(String[] args) {
String str = “this is a cat and is a mice and where is the food”;
String[] strArray = ((String) str).split(" “);
Map<String, Letter> letters = new HashMap<String, Letter>();
for (String temp : strArray) {
Letter col=null;
if(null==(col=letters.get(temp))) {
col = new Letter();
col.setCount(1);
letters.put(temp,col);
}else{
col.setCount(col.getCount()+1);
}
}
Set keys = letters.keySet();
for (String key : keys) {
Letter col = letters.get(key);
System.out.println(“字母” + key + “,次数” + col.getCount());
}
}
}
十五、用面向对象思想+分拣思路统计班级总人数和平均分。
1.创建学生类
package Map;
import java.util.ArrayList;
public class Student {
private String name;
private String no;
private double score;
public Student() {
}
public Student(String name, String no, double score) {
super();
this.name = name;
this.no = no;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
2.创建班级类
package Map;
import java.util.ArrayList;
import java.util.List;
public class ClassRoom {
private String no;
private List stuList;
private double total;
public ClassRoom() {
//避免出现空指针异常
stuList=new ArrayList();
}
public ClassRoom(String no) {
this.no=no;
//避免出现空指针异常
stuList=new ArrayList();
}
public ClassRoom(String no, List stuList, double total) {
super();
this.no = no;
this.stuList = stuList;
this.total = total;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public List getStuList() {
return stuList;
}
public void setStuList(List stuList) {
this.stuList = stuList;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
3.创建测试类,统计班级平均分
package Map;
import cn.bjsxt.Collection.SxtLinkedList;
import java.util.*;
public class Demo02 {
public static void main(String[] args) {
Demo02 test=new Demo02();
test.view(test.count(test.exam()));
}
//模拟考试输入学生成绩
public List exam(){
List list=new ArrayList();
list.add(new Student(“depp”,“a”,90));
list.add(new Student(“depp”,“a”,80));
list.add(new Student(“depp”,“a”,70));
list.add(new Student(“jack”,“b”,70));
return list;
}
//统计分析数据
public Map<String,ClassRoom> count(List list){
Map<String,ClassRoom> map =new HashMap<String,ClassRoom>();
for(Student stu:list){
String no=stu.getNo();
double score=stu.getScore();
ClassRoom room=map.get(no);
//不存在班级编号,新建一个
if(room==null){
room=new ClassRoom(no);
map.put(no, room);
}
//存在则放入
room.getStuList().add(stu);
//计算总分
room.setTotal(room.getTotal()+score);
}
return map;
}
//查看班级总分平均分
public void view(Map<String,ClassRoom> map){
Set keys=map.keySet();
Iterator keysIt=keys.iterator();
while(keysIt.hasNext()){
String no=keysIt.next();
ClassRoom room=map.get(no);
double total=room.getTotal();
double avg=Math.round(room.getTotal()/room.getStuList().size());
System.out.println(“total=”+total+”,avg="+avg);
System.out.println();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值