4.12 练习
- 在例4-25所示的
Performance接口基础上,添加getAllMusicians方法,该方法返回包含所有艺术家名字的Stream,如果对象是乐队,则返回每个乐队成员的名字。例如,如果getMusicians方法返回甲壳虫乐队,则getAllMusicians方法返回乐队名和乐队成员,如约翰·列侬、保罗·麦卡特尼等。
例4-25 表示音乐表演的接口
/** 该接口表示艺术家的演出——专辑或演唱会 */public interface Performance {public String getName();public Stream<Artist> getMusicians();}
根据前面描述的重载解析规则,能否重写默认方法中的
equals或hashCode方法?例4-26所示的
Artists类表示了一组艺术家,重构该类,使得getArtist方法返回一个Optional对象。如果索引在有效范围内,返回对应的元素,否则返回一个空Optional对象。此外,还需重构getArtistName方法,保持相同的行为。
例4-26 包含多个艺术家的Artists类
public class Artists {private List<Artist> artists;public Artists(List<Artist> artists) {this.artists = artists;}public Artist getArtist(int index) {if (index < 0 || index >= artists.size()) {indexException(index);}return artists.get(index);}private void indexException(int index) {throw new IllegalArgumentException(index +"doesn't correspond to an Artist");}public String getArtistName(int index) {try {Artist artist = getArtist(index);return artist.getName();} catch (IllegalArgumentException e) {return "unknown";}}}
