这个布尔值怎么了? [英] what is wrong with this boolean ?

查看:91
本文介绍了这个布尔值怎么了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  String path = "C:\\Users\\User_2\\Pictures";
   
  String files;
  File folder = new File(path);
  
  
  File[] listOfFiles = folder.listFiles(); 
 
  int dot;
  
  for (int i = 0; i < listOfFiles.length; i++) 
  {
   
   if (listOfFiles[i].isFile()){
   files = listOfFiles[i].getName();
   System.out.println(files);
      dot = files.lastIndexOf(".");
   System.out.println(files.substring( dot + 1));
// why this allows equals false......
   System.out.println(files.substring(dot + 1) == "jpg");
  }
  }

推荐答案

此表达式将指向"指向两个不同字符串对象的引用进行比较.您比较引用(指针")和字符串对象.如果将引用与两个不同的字符串对象进行比较,即使它们的值相同,也会给您带来错误.
This expression compares the references that "point" to two different string objects. You compare the references ("the pointers") and the the string objects. This gives you false if you compare th references to two distinct string objects even if their value is the same.
files.substring(dot + 1) == "jpg"


如果要比较对象的内容而不是引用,请使用以下代码:


Use ths code if you want to compare the contents of the objects instead of the references:

"jpg".equals(files.substring(dot + 1))


我称其为"jpg"字符串对象的方法,因为它是一个常数,并且肯定不是null,并且equals()在其参数为null时可以很好地处理.


I call the method of the "jpg" string object because that is a constant and isn''t null for sure and equals() handles well when its parameter is null.


这篇关于这个布尔值怎么了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆