泛型数组案例

用范型实现添加和输出电脑和图书数组

store仓库

public class Store<T> {
	//定义泛型数组
	private T[] array=null;
	//添加数组内容方法
	public void add(T[] array){
		this.array = array;
	}
	//输出数组方法1
	public void show(T[] array){
		for(T s:array){
			if(s!=null){
				System.out.println(s);//因为computer的tostring方法重新,所以不再输出对象地址
			}	
		}
	}
	//输出数组方法2
	public void show2(T[] array){
		for(T t:array){
			if(t!=null){
				if(t instanceof Book){
					Book b=(Book)t;
					System.out.println("Book [ name="+b.getName()+",price="+b.getPrice()+"]");
				}else if(t instanceof Computer){
					Computer c=(Computer) t;
					System.out.println("Computer [ name="+c.getName()+",price="+c.getPrice()+"]");
				}
			}	
		}
	}
}

//电脑类

public class Computer {
	private String name;
	private int price;
	/**
	 * 构造方法
	 * @param name
	 * @param price
	 */
	public Computer(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}
	//重写toString方法
	public String toString() {
		return "Computer [name=" + name + ", price=" + price + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}	
}

//图书类

public class Book {
	private String name;
	private int price;
	/**构造方法
	 * @param name
	 * @param price
	 */
	public Book(String name, int price) {
		super();
		this.name = name;
		this.price = price;
	}
	//get,set
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
}

//检测

public class TextDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 电脑数组
		Computer[] computer=new Computer[]{
				new Computer("华硕",3000),
				new Computer("苹果",4000)
		};	
		//书籍数组
		Book[] book=new Book[2];
		book[0]=new Book("水浒", 300);
		book[1]=new Book("西游记", 200);
		
		//实例化电脑仓库
		Store<Computer> c=new Store<>();
		Store<Book> b=new Store<>();
		c.add(computer);
		b.add(book);
		c.show(computer);
		b.show2(book);
		c.show2(computer);
	}
}

输出结果


Computer [name=华硕, price=3000]
Computer [name=苹果, price=4000]
com.Book@15db9742
com.Book@6d06d69c
Book [ name=水浒,price=300]
Book [ name=西游记,price=200]
Computer [ name=华硕,price=3000]
Computer [ name=苹果,price=4000]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值