泛型 Java语言程序设计 第十九章(示例代码1)
程序员文章站
2022-05-23 14:21:49
...
程序小白,希望和大家多交流,共同学习
//定义泛型类
package stack;
import java.util.ArrayList;
public class GenericStack<E>//泛型类并没有指明数据类型
{
private ArrayList<E> list = new ArrayList<>();
public int getSize()//计算栈的大小
{
return list.size();
}
public E peek()//返回栈顶元素
{
return list.get(getSize() - 1);
}
public void push(E o)//入栈
{
list.add(o);
}
public E pop()//出栈
{
E o = list.get(getSize() - 1);
list.remove(getSize() -1);
return o;
}
public boolean isEmpty()
{
return list.isEmpty();
}
@Override
public String toString()
{
return "stack:" + list.toString();
}
}
//测试栈
package stack;
public class TestGenericStack
{
public static void main(String[] args)
{
GenericStack<String> stack = new GenericStack<>();
stack.push("London");
stack.push("Paris");
stack.push("Berlin");
System.out.println(stack.toString());
GenericStack<Integer> stackInt = new GenericStack<>();
stackInt.push(1);
stackInt.push(2);
stackInt.push(3);
System.out.println(stackInt);
}
}
//通配泛型(受限通配,非受限通配,下限通配)
package stack;
public class WildCardNeedDemo
{
public static void main(String[] args)
{
GenericStack<Integer> intStack = new GenericStack<>();
intStack.push(1);
intStack.push(2);
intStack.push(-2);
System.out.println("The max nummber is " + max(intStack));
}
//public static double max(GenericStack<Number> stack)
//报错显示为不兼容类型,尽管Integer是Number的子类,但是
//Generic<Integer>不是Generic<Number>的子类
//下面的方法就没有错误了,使用通配泛型的受限通配
public static double max(GenericStack<? extends Number> stack)
{
double max = stack.pop().doubleValue();
while (!stack.isEmpty())
{
double value = stack.pop().doubleValue();
if (value > max)
{
max = value;
}
}
return max;
}
}
//非受限通配
package stack;
public class AnyWildCardDemo
{
public static void main(String[] args)
{
GenericStack<Integer> intStack = new GenericStack<>();
intStack.push(1);
intStack.push(2);
intStack.push(-2);
print(intStack);
}
public static void print(GenericStack<?> stack)
{
while (!stack.isEmpty())
{
System.out.print(stack.pop() + " ");
}
}
}
//受限通配的下限通配
package stack;
public class SuperWildCardDemo
{
public static void main(String[] args)
{
GenericStack<String> stack1 = new GenericStack<>();
GenericStack<Object> stack2 = new GenericStack<>();
stack2.push("java");
stack2.push(2);
stack1.push("Sun");
addStack(stack1, stack2);
AnyWildCardDemo.print(stack2);
}
public static <T> void addStack(GenericStack<T> stack1,
GenericStack<? super T> stack2)
{
while (!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
}
}
这里写代码片
上一篇: java集合框架概述