Use of enum (enum) in Android

Source: Internet
Author: User

Brief introduction

An enum, called enumeration, is a new feature introduced in JDK 1.5 and is housed in a Java.lang package.

Creating an enumeration type to use the enum keyword implies that the type created is a subclass of the Java.lang.Enum class (Java.lang.Enum is an abstract class). An enumeration type conforms to a common pattern and Class Enum<E extends Enum<E>> E represents the name of an enumeration type. Each value of the enumeration type is mapped to the protected Enum(String name, int ordinal) constructor, where the name of each value is converted to a string, and the ordinal setting indicates the order in which this setting was created.

The Android website does not recommend using Enums, which consumes much memory (Enums often require more than twice as much memory as static constants.).

Android will assign a single piece of memory to the app when your app is launched. The app's Dex code, heap, and run-time memory allocations are all in this memory.

Usage One: Constants
 Package Com.why.project.androidcnblogsdemo.enumtype; /**  */publicenum  typeenum {cache    ,// cache storage    FILE; // File Store }

 Packagecom.why.project.androidcnblogsdemo.activity;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportCOM.WHY.PROJECT.ANDROIDCNBLOGSDEMO.R;Importcom.why.project.androidcnblogsdemo.enumtype.IConstants;ImportCom.why.project.androidcnblogsdemo.enumtype.LanguageEnum;ImportCom.why.project.androidcnblogsdemo.enumtype.TypeEnum;/*** Created by haiyuking * Used enumeration class Test */ Public classEnumactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_enum); LOG.D ( "Enumactivity", "typeenum.cache=" + Typeenum.cache); // Typeenum.cache=cache
// for general use of enum classes without constructors typeenum typeenum = Typeenum.cache; Createpath (typeenum); } private void Createpath (typeenum createpath) { if(Createpath = = Typeenum . Cache) {LOG.D ("enumactivity", "Create cache directory"); }Else{log.d ("enumactivity", "Create file directory"); } }}
Usage Two: Custom properties and Methods for enum
 PackageCom.why.project.androidcnblogsdemo.enumtype;/*** Language Type*/ Public enumlanguageenum {LANGUAGE ("Language"),//language, key value for sharedpreferences storageLanguage_zh ("zh"),//Chinese, value for sharedpreferences storageLanguage_en ("en"),//EnglishLanguage_es ("es"),//SpanishLanguage_fr ("fr"),//FrenchLanguage_ar ("Ar"),//Ah languageLanguage_ru ("Ru");//Russian    PrivateString language;//Custom Properties    /**constructor, the enumeration type can only be private*/Languageenum (String language) { This. Language =language; }    //Custom Methods     PublicString GetLanguage () {returnlanguage; }}

 Packagecom.why.project.androidcnblogsdemo.activity;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportCOM.WHY.PROJECT.ANDROIDCNBLOGSDEMO.R;Importcom.why.project.androidcnblogsdemo.enumtype.IConstants;ImportCom.why.project.androidcnblogsdemo.enumtype.LanguageEnum;ImportCom.why.project.androidcnblogsdemo.enumtype.TypeEnum;/*** Created by haiyuking * Used enumeration class Test */ Public classEnumactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_enum);        log.d ("enumactivity", "LanguageEnum.LANGUAGE_zh.getLanguage () =" + LanguageEnum.LANGUAGE_zh.getLanguage ());//LanguageEnum.LANGUAGE_zh.getLanguage () =zh    }}
Alternative Solutions

Interface variables

Because the interface automatically sets the member variable to static (static), immutable (final), this prevents some cases from mistakenly adding new constants. This also makes the code look simpler and clearer. At the same time, a simple test shows that the same interface (bytecode file) occupies 209 bytes or so, while the class (bytecode file) occupies about 366 bytes of space. Fewer bytecode files mean less cost to load and maintain. In addition, when the JVM loads the interface, it does not need to worry about the extra features provided by the class (such as overloading, dynamic binding of methods, etc.), so loading is faster.

 PackageCom.why.project.androidcnblogsdemo.enumtype;/*** Created by haiyuking * Used*/ Public Interfaceiconstants {//The interface automatically sets the member variable to static (static), immutable (final)String LANGUAGE = "LANGUAGE"; String Language_zh= "zh"; String language_en= "en"; String Language_es= "Es"; String Language_fr= "FR"; String Language_ar= "AR"; String Language_ru= "Ru";}

 Packagecom.why.project.androidcnblogsdemo.activity;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.util.Log;ImportCOM.WHY.PROJECT.ANDROIDCNBLOGSDEMO.R;Importcom.why.project.androidcnblogsdemo.enumtype.IConstants;ImportCom.why.project.androidcnblogsdemo.enumtype.LanguageEnum;ImportCom.why.project.androidcnblogsdemo.enumtype.TypeEnum;/*** Created by haiyuking * Used enumeration class Test */ Public classEnumactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.activity_enum);        log.d ("enumactivity", "iconstants.language_zh=" + Iconstants.language_zh);//Iconstants.language_zh=zh    }}

Resources

java enum (enum) using a detailed + summary

A detailed explanation of Java enum usage

Is it recommended to use enum enum in Android?

Use of enum (enum) in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.