java - 一切正常,但我不明白它是如何工作的?
问题描述
我制作了一个应用程序,在其中显示所有歌曲、专辑、艺术家、流派和播放列表。
我正在检查我的代码,因为我收到一个错误,因为我正在检查作为参数传递的字符串是否与我的专辑类 getGenre() 方法中的字符串相同,该方法返回一个字符串。
我通过更改解决了这个错误
public ArrayList<Song> getSongsByGenre(String genreName) {
ArrayList<Song> songsByGenre = new ArrayList<>();
for (Song song : songs) {
String currentSongGenre = song.getGenre();
if (currentSongGenre.equals(genreName))
songByGenre.add(song);
}
}
至
public ArrayList<Song> getSongsByGenre(String genreName) {
ArrayList<Song> songsByGenre = new ArrayList<>();
for (Song song : songs) {
String currentSongGenre = song.getGenre();
if (Objects.equals(currentSongGenre, genreName))
songsByGenre.add(song);
}
}
Objects.equals 和 just currentSongGenre.equals(genreName); 有什么区别??
另外我不明白的是,当我在 logcat 中记录了“ currentSongGenre ”、“ genreName ”和if 语句的值时。
Log.d(TAG, "value currentSongGenre: " + currentSongGenre);
Log.d(TAG, "value genreName: " + genreName);
Log.d(TAG, "value ifstat: " + currentSongGenre + " Equals " + genreName);
Logcat 调试
SongList: value currentSongGenre: null
SongList: value genreName: Hip-Hop/Rap
SongList: value ifstat: null Equals Hip-Hop/Rap
那么当两个字符串值明显不同时它是如何工作的呢?
ps 这就是我设置流派的方式,如果您需要更多代码,请告诉我,因为它有很多代码。
我使用 2 个哈希图:
songIdToGenreIdMap &genreIdToGenreNameMap,在第一个中,我添加了设备上找到的所有歌曲 ID 和流派 ID,第二个用于获取流派名称。
String currentGenreID = songIdToGenreIdMap.get(Long.toString(song.getId()));
String currentGenreName = genreIdToGenreNameMap.get(currentGenreID);
song.setGenre(currentGenreName);
解决方案
在您的第一个块中,您不是与“流派名称”进行比较,而是与“流派”进行比较。
if (currentSongGenre.equals(genre))
应该
if (currentSongGenre.equals(genreName))
推荐阅读
- java - 显示进度条以等待繁重的计算
- android - Gradle 需要很长时间才能构建
- ios - 如何使用 Kingfisher 在 UIButton 的 setBackgroundImage 期间设置 indicatorType
- node.js - Jenkins 安装 nodejs 插件失败
- xamarin - 不同平台的覆盖视图
- image - 如何在颤动的 BoxDecoration 中显示来自网络的图像?
- php - 将texarea格式转换为php
- go - 如何使用 confluent-kafka-go 获取 kafka 代理错误的事件
- pyspark - Spark 流式传输到 Power BI
- ckeditor - 浏览 CKEditor 5 中的不同部分