zoukankan      html  css  js  c++  java
  • Java学习-泛型综合练习

    泛型的用法是在容器后面添加<Type>
    Type可以是类,抽象类,接口
    泛型表示这种容器,只能存放<Type>

    1.设计支持泛型的二叉树,具有add(),Inorder()中序遍历方法

     1 package generic;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 public class Node<T extends Comparable<T>> {
     7     public Node<T> leftNode;
     8     public Node<T> rightNode;
     9     public T value;
    10 
    11     public void add(T v) {
    12         if (value == null)
    13             value = v;
    14         else {
    15             if (v.compareTo(value) < 0) { // 新加入的值比当前结点的值更小,把他放到当前结点的左结点
    16                 if (leftNode == null) {
    17                     leftNode = new Node<T>();
    18                 }
    19                 leftNode.add(v);
    20             } else {
    21                 if (rightNode == null) {
    22                     rightNode = new Node<T>();
    23                 }
    24                 rightNode.add(v);
    25             }
    26         }
    27     }
    28 
    29     public List<T> Inorder() { // 中序遍历,本质是递归
    30         List<T> values = new ArrayList<T>();
    31         if (leftNode != null) {
    32             values.addAll(leftNode.Inorder());
    33         }
    34         values.add(value);
    35         if (rightNode != null) {
    36             values.addAll(rightNode.Inorder());
    37         }
    38         return values;
    39     }
    40 
    41     public static void main(String[] args) {
    42         // 支持泛型的Node既可以支持Integer,也可以支持Float
    43         Node<Integer> root = new Node<>();
    44         for (int i = 0; i < 10; i++) {
    45             root.add((int) (Math.round(Math.random() * 100)));
    46         }
    47         System.out.println(root.Inorder());
    48 
    49         Node<Float> fRoot = new Node<>();
    50         for (int i = 0; i < 10; i++) {
    51             fRoot.add((float) (Math.random() * 100));
    52         }
    53 
    54         System.out.println(fRoot.Inorder());
    55     }
    56 }

    效果图:

  • 相关阅读:
    python--io多路复用之select实现
    python--基于socket网络编程
    python--面向对象编程之学生选课系统练习
    python--异常处理
    python--面向对象之三个特性:封装、继承、多态
    python--反射机制
    python--生成器和迭代器
    elasticsearch 创建索引
    elasticsearch 集群搭建
    linux 安装Mosquitto
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/12230689.html
Copyright © 2011-2022 走看看