我是java中枚举的新手,我很困惑为什么这段代码编译得很好enumScale5{GOOD(),BETTER(),BEST();staticScale5s=GOOD;}但是这段代码失败了:enumScale5{GOOD(),BETTER(),BEST();Scale5s=GOOD;}我收到错误:初始化程序对静态字段的非法引用。我不明白原因。我在枚举方面相对缺乏经验,所以请把它转给我。非常感谢!这里问的问题Cannotrefertothestaticenumfieldwithinaninitializer?与我所问的完全相反。在我的例子中,将s声明为静态可以很好地编译代码。
我正在编写一些需要定义大量常量的代码。它主要处理Marketplace常量(可能是美国、英国、印度、日本)和关联的MarketplaceMerchantMapping,它基本上将MerchantID映射到市场ID。例如:publicenumMarketplace{US("US"),JP("JP"),UK("UK"),IN("IN"),NZ("NZ"),CA("CA"),FR("FR"),......//Thiscouldgouptosome400marketplacesprivatefinalStringstringValue;publicbooleanisWest(){returnt
为什么每次运行javamain时都有不同的hashCode值?请看下面的示例代码。interfacetestInt{publicintgetValue();}enumtestimplementstestInt{A(1),B(2);privateintvalue;privatetest(intvalue){this.value=value;}publicintgetValue(){returnthis.value;}}每次运行,publicstaticvoidmain(String[]args){System.out.println(test.A.hashCode());}控制台上会有不
我正在看一本关于编程的书,我遇到了这样一件事:publicstaticenumMonth{JANUARY(1),FEBRUARY(2),MARCH(3),APRIL(4),MAY(5),JUNE(6),JULY(7),AUGUST(8),SEPTEMBER(9),OCTOBER(10),NOVEMBER(11),DECEMBER(12);Month(intindex){this.index=index;}枚举实例后括号中的数字是什么意思?它是枚举构造函数吗? 最佳答案 Whatdoesanumberinparenthesesmean
最近,我注意到,有可能:classTest{publicenumSeason{WINTER,SPRING,SUMMER,FALL}Seasonfield=Season.WINTER.SPRING;//whyisWINTER.SPRINGpossible?}这有什么原因吗? 最佳答案 当您在Java中访问对象的静态成员(包括枚举)时,编译器会有效地用其静态类型替换该对象。更具体地说,classExampleClass{staticintstaticField;staticvoidstaticMethod(){ExampleClasse
考虑下面的枚举类publicenumClassA{CHECK1("X",0),CHECK2("Y",2),CHECK3("Z",1);privatefinalStringid;privatefinalStringcdValue;privateClsA(Stringid,StringcdValue){this.id=id;this.cdValue=cdValue;}privateStringgetId(){returnid;}privateStringgetCdValue(){returncdValue;}privatestaticfinalListcdValues=newArrayLi
请看这个link.JoshuaBloch在他的EffectiveJava一书中说请注意,操作常量是从一个在创建常量后运行的静态block。Tryingtomakeeachconstantputitselfintothemapfromitsownconstructorwouldcauseacompilationerror.这是一件好事,因为它会导致NullPointerException如果它是合法的。Enumconstructorsaren’tpermittedtoaccesstheenum’sstaticfields,exceptforcompile-timeconstantfiel
如何返回这样的枚举?在我返回一个int之前,如果否则返回0,如果是则返回1,如果其他则返回2。但这不是一个好方法。那么应该怎么做呢。我的代码:classSomeClass{publicenumdecizion{YES,NO,OTHER}publicstaticenumyourDecizion(){//scanneretcif(x.equals('Y')){returnYES;}elseif(x.equals('N')){returnNO;}else{returnOTHER;}}} 最佳答案 我不知道“//扫描仪等”是什么。确实如此,
我想在一个集合中存储一个名为App的类型。App需要是一个实现了App接口(interface)的枚举。SetmyApps;我已经这样定义了接口(interface)......interfaceApp>{}这几乎可以工作,例如,你不能这样做......classMyClassimplementsApplication{}但是,你可以这样做......enumMyEnumimplementsApplication{}classMyclassimplementsApplication{}这是错误的。我只希望枚举能够实现这个接口(interface),我该如何强制执行?
我有一个私有(private)的枚举,不会在类外公开。无论如何我可以做那种类型的静态导入,这样我就不必每次都输入枚举类型了吗?或者有更好的写法吗?示例:packagekip.test;importstatickip.test.Test.MyEnum.*;//compileerrorpublicclassTest{privatestaticenumMyEnum{DOG,CAT}publicstaticvoidmain(String[]args){MyEnumdog=MyEnum.DOG;//thisworksbutIdon'twanttotype"MyEnum"MyEnumcat=CAT