有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确地重现?

我有一个歌曲列表,我正在尝试将标题作为一个字符串生成 比如说

ILo<Song> slist2 = new ConsLo<Song>(this.help,
        new ConsLo<Song>(this.hotelc, this.mtlos));

应该制作“帮助,加利福尼亚酒店”,但我一直得到“帮助,加利福尼亚酒店,” 这是我的密码

public String forCons(Song first, ILo<Song> rest) {
    if(rest.equals(null)) {
        return first.title;
    }
    return first.title + ", " + rest.accept(this);
}

方法accept只是在rest上递归方法

我也试过这个

public String forCons(Song first, ILo<Song> rest) {
    ILo<Song> mt = new MtLo<Song>();
    if(rest.equals(mt)) {
        return first.title;
    }
    return first.title + ", " + rest.accept(this);
}


public <R> R accept(ILoVisitor<R, T> ilov) {
  return ilov.forCons(this.first, this.rest);
}

在哪里

// A visitor for the ILo<T> classes that 
// and produces the result of the type R
interface ILoVisitor<R, T>

ILo代表T型项目列表,ConsLo代表T型项目非空列表


共 (2) 个答案

  1. # 1 楼答案

    我真的不明白你为什么要为列表这样的数据结构使用自定义类
    使用标准库中的简单List<Song>怎么样

    int size;
    
    public static String forCons(Song first, List<Song> rest) {
        size = rest.size();        
    
        if(size == 1) {     // last element
            return first.getTitle();
        }
        return first.getTitle() + ", " + forCons(rest.get(0), rest.subList(1, size));
    }
    
  2. # 2 楼答案

    改变

    if(rest.equals(null)) {
        return first.title;
    }
    

    if(rest == null ){
        return first.title;
    }