泛型(1)_容器

来源:互联网 发布:windows 8.1哪个版本好 编辑:程序博客网 时间:2024/06/07 01:51

1. 堆栈

public class LinkedStack<T> {private static class Node<U> {private U item;private Node<U> next;public Node() {item = null;next = null;}public Node(U item, Node<U> next) {this.item = item;this.next = next;}boolean end() {return item == null && next == null;}}private Node<T> top = new Node<T>();public void push(T item) {top = new Node<T>(item, top);}public T pop() {T result = top.item;if(!top.end()) {top = top.next;}return result;}public static void main(String[] args) {LinkedStack<String> stack = new LinkedStack<String>();for(String s : "a b c d".split(" ")) {stack.push(s);}String result = null;while((result=stack.pop()) != null) {System.out.print(result + " ");}System.out.println();}}
//outputd c b a

2. 随机查询

import java.util.ArrayList;import java.util.List;import java.util.Random;public class RandomList<T> {private List<T> storage = new ArrayList<T>();private Random random = new Random(47);public void add(T item) {storage.add(item);}public T select() {return storage.get(random.nextInt(storage.size()));}public static void main(String[] args) {RandomList<String> rList = new RandomList<String>();for(String s : "a b c d".split(" ")) {rList.add(s);}for(int i=0; i<20; i++) {System.out.print(rList.select() + " ");}}}
//outputc b c a a c a b c c b d b a a c d a d c



 

0 0
原创粉丝点击