梳理8--泛型
详细:https://www.cnblogs.com/coprince/p/8603492.html
1. 接口:
2. 实现了此接口的类
3. 使用
打印:
例子:
/** * @author sr * @date 2021/1/18 */ public class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void say(){ System.out.println("i am "+ getUsername()); } /** * 最好重写!! * @return */ @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
/** * @author sr * @date 2021/1/18 */ public interface Super<T> { /** * 添加数据 * @param data */ void add(T data); /** * 删除结点 * @param index */ public void delete(int index); /** * 修改 * @param index * @param newData */ void upDate(int index,T newData); /** * 打印 */ void print(); /** * 查 * @param index * @return */ T get(int index); /** * 长度 * @return */ int size(); }
/** * @author sr * @date 2021/1/18 */ public class SuperLink<T> implements Super<T> { private Node head; private int size; /** * 头插法 * @param data */ @Override public void add(T data){ Node newHead = new Node(data,null); newHead.setNext(head); head = newHead; size++; } /** * 删除结点 * @param index */ @Override public void delete(int index){ if (index == 0){ Node node = getNode(index); head = node.getNext(); }else { Node node = getNode(index - 1); node.setNext(node.getNext().getNext()); } size--; } /** * 修改指定结点的值 * @param index * @param newData */ @Override public void upDate(int index, T newData){ Node node = getNode(index); node.setData(newData); } /** * 查找指定节点的值 * @param index * @return */ @Override public T get(int index){ return (T)(getNode(index).getData()); } /** * 查找指定结点 * @param index * @return */ public Node getNode(int index){ Node node = head; for (int i = 0; i < index; i++) { node = node.getNext(); } return node; } /** * 打印链表的全部 */ @Override public void print(){ Node node = head; while (node != null){ System.out.println((T)node.getData()); node = node.getNext(); } } /** * 长度 * @return */ @Override public int size() { return size; } }
/** * @author sr * @date 2021/1/18 */ public class Test { public static void main(String[] args) { // Animal animal = new Dog(); // animal.eat(); // animal.breath(); //SuperLink和SuperArray同时implement Super //需要修改s时,只需要修改 new SuperArray() 即可 Super<User> s = new SuperLink<>(); s.add(new User("sr","123")); s.add(new User("sr2","1234")); s.print(); for (int i = 0; i < s.size(); i++) { System.out.println(s.get(i)); s.get(i).say(); } } }