当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Enum equals()用法及代码示例


如果此枚举对象与定义的对象相同,则 Enum 类的 equals() 方法返回 true。

用法

public final boolean equals(Object other)

覆盖

Enum 类的 equals() 方法覆盖了 Object 类的 equals() 方法。

参数

other- 它是要与此枚举进行比较的对象。

返回值

如果定义的对象等于此枚举,则 equals() 方法返回 true。

例子1

public class Enum_equalsMethodExample1 {
enum Colour{
red,reD;
    }
public static void main(String[] args) {
        Colour red,reD;
        red=Colour.red;
reD=Colour.reD;
if(red.equals(reD)){
System.out.println("Both are equal");
        }
else{
System.out.println("red and reD are not equal because of case sensitivity");
        }
    }
}

输出:

red and reD are not equal because of case sensitivity

例子2

import java.util.Scanner;

public class Enum_equalsMethodExample2 {

enum SPS{

Stone,Paper,Scissor;
    }

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

System.out.println("Choose amongst the following:");

for(SPS game:SPS.values()){

System.out.println(game);
        }

System.out.print("# ");String str = scanner.next();

        SPS Stone;

        SPS Paper;

        String Scissor;

        Scissor =SPS.Scissor.toString();

        Stone =SPS.Stone;

        Paper=SPS.Paper;

if(Paper.toString().equals(str)) {

System.out.println("There is a Tie");

        }
else if(str.equals(Stone.toString())){

System.out.println("Sorry ! You lose.");
        }
else if(str.equals(Scissor)){
System.out.println("Hurray! Yor won.");
        }
    }
}

输出:

Choose amongst the following:
Stone
Paper
Scissor
#

例子3

public class Enum_equalsMethodExample3 {

enum movie{

Don,DDlJ,Fan,Zero;
   }

public static void main(String[] args) {

movie Don,DDLJ,Fan,Zero;

   Don=movie.Don;

System.out.println("Q In which movie Shah rukh khan has played a dual role ?");

        String obj="Don";

        Boolean b1 =obj.equals(Don.toString());

if(b1==true){

System.out.println("Ans. "+obj);

System.out.println("Your answer is correct.");
        }

else{

System.out.println("Sorry!You Failed.\n The Correct answer is Don.");
        }
    }
}

输出:

Q In which movie Shah rukh khan has played a dual role ?
Ans. Don
Your answer is correct.



相关用法


注:本文由纯净天空筛选整理自 Java Enum equals() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。