zoukankan      html  css  js  c++  java
  • Java Arrays Tutorial (3)

    Java Arrays Tutorial (3)

    Data types have a specific set of values. A byte cannot hold a value larger than 127 and an int cannot hold a value larger than 2,147,483,647. You can also create your own data types that have a finite set of legal values. A programmer created data type with a fixed set of values is an enumerated data type.

    In Java, you create an enumerated data type in a statement that uses the keyword enum, an identifier for the type, and a pair of curly braces that contain a list of the enum constants, which are the allowed values for the type. For example, the following code creates an enumerated type named Month that contains 12 values:

    Enum Month{JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

    After you create an enumerated data type, you can declare variables of that type. For example, you might declare the following:

    Month birthMonth;

    You can assign any of the enum constants to the variables. Therefore, you can code a statement such as the following:

    birthMonth = Month.MAY;

    An enumeration type like Month is a class, and its enum constants act like instantiated from the class, including having access to the methods of the class.

    Creating an enumeration type provides you with several advantages:

    (1). If you did not create an enumerated type for month values, you could use another type, for example, ints or Strings. The problem is that any value could be assigned to an int or String variable, but only the 12 allowed values can be assigned to a Month.

    (2). If you did not create an enumerated type for month values, you could create another type to represent months, but invalid behavior could be applied to the values. For example, you could add or substract two months, which is not logical. Programmers say using enums makes the values type-safe. Type-safe describes a data type for which only appropriate behaviors are allowed.

    (3). The enum constants provide a form of self-documentation. Someone reading your program might misinterpret what 9 means as a month value, but there is less confusion when you use the identifier OCT.

    (3). As with other classes, you can also add methods and other fields to an enum type.

  • 相关阅读:
    [洛谷P3931]SAC E#1
    洛谷 P4127 [AHOI2009]同类分布 解题报告
    洛谷 P4475 巧克力王国 解题报告
    洛谷 P4148 简单题 解题报告
    洛谷 P2463 [SDOI2008]Sandy的卡片 解题报告
    洛谷 P4211 [LNOI2014]LCA 解题报告
    洛谷 P4074 [WC2013]糖果公园 解题报告
    AT1219 歴史の研究 解题报告
    洛谷 P4137 Rmq Problem /mex 解题报告
    THUWC2019 摸鱼记
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3153345.html
Copyright © 2011-2022 走看看