/* *
- @Created with IntelliJ IDEA.
- @Description: 泛型 (Generic)
-
实现一个通用栈。
-
想法1:数组--》Object
-
想法2:使用java的泛型
- @Author:WangGuiyang
- @Date:2020/4/5 9:11
*/
///**
// * : 只是一个占位符,标识当前类是一个泛型类 可以有多个参数
// * 使用方式:MyStack myStack = new MyStack<>();
// *
// * 泛型的意义是什么?
// * 1、在编译的时候,会进行类型的检查
// * 2、可以自动进行类型的转换
// *
// * 注意:
// * 1、不能够new 一个泛型的数组 new T[10];
// * 2、在使用的时候 一定要指定泛型类型的参数
// * 3、泛型到底是怎么编译的?
// * a:泛型是编译时间的一种机制,在运行的时候 没有泛型这个概念
// * 导致:在运行完代码,看类型的组成时,没有尖括号内容。
// * 泛型类型的组成 不包含<>
// * b:机制–》擦除机制。在编译的时候,被擦除为Object了。
// * 但是类型的检查是根据你给定的泛型参数 来进行类型检查的。并不是替换为当前的类型了。
// *
// * 4、MyStack myStack3 = new MyStack<>(); 简单类型不能当做 泛型类型的参数
// *
// * 5、MyStack[] myStack3 = new MyStack[3]; 不能new 泛型 对象数组
// *
// * 6、在泛型类中,静态方法 不能使用泛型类型的泛型参数
// * public static T findMaxNum (T[] array) {}
// * 静态的不依赖于对象。
// * public static T findMaxNum (T[] array) {} ==> 泛型方法
// * 7、泛型类型的父子关系:
// * MyArrayList 不是 MyArrayList 的父类型
// * 虽然Object 是 Number的父类类型 但是 我们说过
// * <>的内容 是不参与类型组成的。
// * * @param
// */
class MyStack {
public T[] elem;
public int usedSize;
public MyStack() {
this.elem = (T[])new Object[10];
this.usedSize = 0;
}
public void push(T val) {
this.elem[this.usedSize] = val;
this.usedSize++;
}
public T pop() {
T data = this.elem[this.usedSize-1];
this.usedSize--;
return data;
}
public T peek() {
return this.elem[this.usedSize-1];
}
}
class Person {
}
public class TestDemo {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person);
MyStack<Integer> myStack1 = new MyStack<>();
MyStack<String> myStack2 = new MyStack<>();
System.out.println(myStack1);
System.out.println(myStack2);
}
public static void main3(String[] args) {
MyStack<Integer> myStack1 = new MyStack<>();
myStack1.push(1);
myStack1.push(4);
MyStack<String> myStack2 = new MyStack<>();
myStack2.push("bit");
myStack2.push("hello");
}
public static void main2(String[] args) {
MyStack myStack = new MyStack ();
myStack.push(1);
myStack.push("bit");
String num = (String)myStack.pop();
}
public static void main1(String[] args) {
MyStack<Integer> myStack = new MyStack<>();
myStack.push(1);
myStack.push(4);
int num = myStack.pop();
}
}