范型数组案例

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

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]

猜你喜欢

转载自blog.csdn.net/weixin_43343423/article/details/88995651