Java中泛型ArrayList调用add方法报类型不匹配错误如何解决
问题根源
- 你定义的
artistaMusica是泛型为Song的ArrayList,Java泛型校验规则要求该列表仅能添加pt.ulusofona.aed.deisiRockstar2021.Song类的实例 - 报错行
artistaMusica.add(newTag)传入的newTag是String类型,和列表要求的元素类型不匹配,因此触发编译错误
解决方案
结合你的方法名ADD_TAGS的业务语义,你需要实现的是给匹配到的艺术家对应的Song对象新增标签,而非往artistaMusica列表中新增元素,修改逻辑如下:
- 遍历到匹配的艺术家时,先取出当前对应的
Song对象 - 调用
Song对象的标签添加方法完成标签新增,无需操作artistaMusica列表的新增接口
修改后的代码示例:
public static void ADD_TAGS(ArrayList<Song> artistaMusica,String artista,String newTag){ long start = System.currentTimeMillis(); String tempArtist = ""; for(int i = 0 ; i < artistaMusica.size() ; i++) { tempArtist = artistaMusica.get(i).getnomeArtista().replace("']", "").replace("['", "").trim(); if (artista.equals(tempArtist)) { // 取出当前匹配的Song对象 Song currentSong = artistaMusica.get(i); // 调用Song类的新增标签方法(需提前在Song类中实现对应逻辑) currentSong.addTag(newTag); System.out.println(artista+" | " + newTag ); } } long end = System.currentTimeMillis(); System.out.println("(took "+(end-start)+" ms)\n"); }
如果你的Song类尚未实现标签存储和添加逻辑,需要先补充对应代码:
public class Song { // 原有类属性、构造方法、get/set方法省略 private List<String> tags = new ArrayList<>(); // 新增标签方法 public void addTag(String tag) { this.tags.add(tag); } // 按需补充获取标签列表的方法 public List<String> getTags() { return this.tags; } }
如果你确实有往
artistaMusica列表新增元素的业务需求,需要先将newTag以及其他Song类的必填属性封装为Song实例,再调用add方法传入该实例即可。
内容的提问来源于stack exchange,提问作者Francisco Lopes
相关产品推荐
相关产品推荐

