歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> JAVA中equals()方法的重要性

JAVA中equals()方法的重要性

日期:2017/3/1 10:44:14   编辑:Linux編程

對於對象比較使用equals()方法的重要性,這裡以String類為例進行了比較。

  1. /**
  2. * 對於對象比較使用equals()方法的重要性,這裡以String類為例進行了比較。
  3. * @author HAN
  4. *
  5. */
  6. public class TestEqual {
  7. public TestEqual(){
  8. testMethod();
  9. }
  10. void testMethod(){
  11. String str=new String("Gaowen HAN");
  12. String str2=new String("Gaowen HAN");
  13. String str3="Gaowen HAN";
  14. String str4="Gaowen HAN";
  15. if(str.equals(str2)){
  16. System.out.println("str is equal to str2");
  17. }else{
  18. System.out.println("str is not equal to str2");
  19. }
  20. if(str3==str4){
  21. System.out.println("str is equal to str2");
  22. }else{
  23. System.out.println("str is not equal to str2");
  24. }
  25. if(str==str2){
  26. System.out.println("str is equal to str2");
  27. }else{
  28. System.out.println("str is not equal to str2");
  29. }
  30. if(str.equals(str3)){
  31. System.out.println("str is equal to str2");
  32. }else{
  33. System.out.println("str is not equal to str2");
  34. }
  35. if(str==str3){
  36. System.out.println("str is equal to str2");
  37. }else{
  38. System.out.println("str is not equal to str2");
  39. }
  40. }
  41. public static void main(String[] args) {
  42. new TestEqual();
  43. }
  44. }
Copyright © Linux教程網 All Rights Reserved