如何修改此代码以使其支持数组返回值?

时间:2011-04-11 06:47:34

标签: java

public Solution getReferenceSolution(Problem p)
        throws UnsupportedOperationException {
        Solution result;

        if (!haveReferenceSolution)
            throw new UnsupportedOperationException("Domain.getReferenceSolution: A getReferenceSolution() method has not been specified for this domain.  If its use is required, please specify one using setEquivalenceClasses() or by overriding Domain.getReferenceSolution().");
        else {
            if (haveBooleanSolutionCutoff)
                result = findNearestEquivalenceClass(p).applyTo(p, booleanSolutionCutoff);
            else
                result = findNearestEquivalenceClass(p).applyTo(p);
        }

        result.setIsReferenceSolution(true);

        return result;
    }

3 个答案:

答案 0 :(得分:1)

如果你只需要一个解决方案,但是一个地方需要多个解决方案,我建议你有两种方法;像这样的东西:

public Solution getReferenceSolution(Problem p)
{
    // Code as before
}

public List<Solution> getAllSolutions(Problem p)
{
    // Whatever you need to do here
}

请注意,从方法名称开始,您是在寻找一个解决方案还是多个解决方案;在这种情况下我不会使用重载,因为你正在尝试做不同的事情。

答案 1 :(得分:0)

你的意思是这样吗?

public Solution[] getReferenceSolution(Problem p) {
    Solution result;
    // set result.
    return new Solution[] { result };
}

答案 2 :(得分:0)

也许更好地返回一个集合,例如ArrayList

public List<Solution> getReferenceSolution(Problem p)
    throws UnsupportedOperationException {

    List<Solution> solutions= new ArrayList<Solution>();

    Solution result = ... // your code here

    solutions.add(result);

    return solutions;
}

或许您想将List作为参数传递给getReferenceSolution方法并将其填入方法内?

public void getReferenceSolution(Problem p, List<Solution> solutions)
    throws UnsupportedOperationException {

    // your code to fill the list using solutions.add(Solution)

}