如何在validCell中修改传入validCell的“list”,然后返回修改后的列表? validCell接受参数并检查是否可以从r& amp;给出的起始点找到拼写出“单词”的单元格的路径。 cellForWord中的for循环的c。我认为我所拥有的是正确的。
public class GoodWordOnBoardFinder implements IWordOnBoardFinder {
@Override
public List<BoardCell> cellsForWord(BoggleBoard board, String word) {
// TODO Auto-generated method stub
List<BoardCell> list = new ArrayList<BoardCell>();
//Loop through each cell on board to find a starting point
for(int r=0; r < board.size(); r++)
{
for(int c=0; c < board.size(); c++)
{
if(validCell(board, r, c, list, word, 0))
return list;
//***HOW to get populated list NOT Blank list???
}
}
return null;
}
public boolean validCell(BoggleBoard theBoard, int row, int col, List<BoardCell> cList, String theWord, int letterIndex ){
BoardCell cell = new BoardCell(row, col);
String letter = theWord.substring(letterIndex, letterIndex+1);
//Check the whole world has been found
if(letterIndex >= theWord.length())
return true;
//Check if row or column is off the board
if(row > theBoard.size() || col > theBoard.size())
return false;
//Check if cell has already been visited
if(cList.contains(cell))
return false;
//Check if cell face isn't the letter we're looking for
if(!theBoard.getFace(row, col).equals(letter))
{
//Make sure the letter isn't a Q bc Boggle is special
if(!(theBoard.getFace(row, col).equals("Qu") && letter.equals("q")))
return true;
}
cList.add(cell);
//Check all neighboring cells for letters of the word
int[] rdelta = {-1,-1,-1, 0, 0, 1, 1, 1};
int[] cdelta = {-1, 0, 1,-1, 1,-1, 0, 1};
for(int k=0; k < rdelta.length; k++){
if (validCell(theBoard, row+rdelta[k], col+cdelta[k], cList, theWord, letterIndex+1))
return true;
}
cList.remove(cell);
return false;
}
}
答案 0 :(得分:0)
在Java中,对象按值传递(参见this response)。这实质上意味着传入对象本身的引用,并将其转换回原始对象,而不是对象的副本。你可以修改列表而不用担心返回它,因为任何修改都会保留。
Example:
List<String> test = new ArrayList<String>();
test.add("Test 1");
OtherClass otherClass = new OtherClass(test);
...
otherClass.modifyList(test);
...
System.out.println(test.size());
在此示例中,modifyList
将假设将另一个字符串添加到传入列表中。
答案 1 :(得分:0)
您在validCell中所做的任何更改cList
都会自动反映到原始列表中。
Java是按值传递的:在这种情况下,它传递引用的值。所以两者都将指向同一个对象。在validCell中对cList
所做的任何更改都将反映在list
上。
答案 2 :(得分:0)
考虑将列表转换为类成员。那么你不必将它传递给方法:
public class GoodWordOnBoardFinder implements IWordOnBoardFinder {
// The board
List<BoardCell> board;
// methods
public boolean validCell(BoggleBoard theBoard, int row, int col, String theWord, int letterIndex ){
// access/modify the board (= what you called cList)
}
}