4.12 练习

  1. 在例4-25所示的Performance接口基础上,添加getAllMusicians方法,该方法返回包含所有艺术家名字的Stream,如果对象是乐队,则返回每个乐队成员的名字。例如,如果getMusicians方法返回甲壳虫乐队,则getAllMusicians方法返回乐队名和乐队成员,如约翰·列侬、保罗·麦卡特尼等。

例4-25 表示音乐表演的接口

  1. /** 该接口表示艺术家的演出——专辑或演唱会 */
  2. public interface Performance {
  3. public String getName();
  4. public Stream<Artist> getMusicians();
  5. }
  1. 根据前面描述的重载解析规则,能否重写默认方法中的equalshashCode方法?

  2. 例4-26所示的Artists类表示了一组艺术家,重构该类,使得getArtist方法返回一个Optional对象。如果索引在有效范围内,返回对应的元素,否则返回一个空Optional对象。此外,还需重构getArtistName方法,保持相同的行为。

例4-26 包含多个艺术家的Artists

  1. public class Artists {
  2. private List<Artist> artists;
  3. public Artists(List<Artist> artists) {
  4. this.artists = artists;
  5. }
  6. public Artist getArtist(int index) {
  7. if (index < 0 || index >= artists.size()) {
  8. indexException(index);
  9. }
  10. return artists.get(index);
  11. }
  12. private void indexException(int index) {
  13. throw new IllegalArgumentException(index +
  14. "doesn't correspond to an Artist");
  15. }
  16. public String getArtistName(int index) {
  17. try {
  18. Artist artist = getArtist(index);
  19. return artist.getName();
  20. } catch (IllegalArgumentException e) {
  21. return "unknown";
  22. }
  23. }
  24. }