尝试将数组列表与方法和构造函数一起使用.这可以优化吗



我已经在Codecademy上练习了一段时间的编码,我决定自己玩ArrayLists。Codecademy只向我展示了如何使用println来实现我想要打印到控制台的值。相反,我想,如果我想使用构造函数和方法呢?我是在玩了一段时间后才想到这个的,但由于我还是一个初学者,如果我能更好地优化它以获得相同的结果,我很想知道怎么做。非常感谢您抽出时间!

import java.util.ArrayList;
public class List {
//set variables to be used in constructor and custom method
String itemValue;
int itemIndex;
//declare shoppingList array
ArrayList<String> shoppingList = new ArrayList<String>();
{
//set what is inside the shoppinglist array
shoppingList = new ArrayList<String>();
shoppingList.add("Pumpkin");
shoppingList.add("Carving Kit");
shoppingList.add("Halloween Decorations");
shoppingList.add("Face Paint");
}
public List(String itemName) {
//set the value of what we want to find our index for to itemValue
itemValue = itemName;
}
public void getIndex() {
//sets the index of itemValue to itemIndex then prints the name and index
itemIndex = shoppingList.indexOf(itemValue);
System.out.println("The index of " + itemValue + " is " + itemIndex + "!");
}
public static void main(String[] args) {
//declare shoppingIndex object
List shoppingIndex = new List("Face Paint");
//Calls get index to print our Item name and its index in shoppingList
shoppingIndex.getIndex();
}
}

避免"//"注释,依赖可读代码和javadoc

java7 之后

ArrayList<String> shoppingList = new ArrayList<String>();

成为

ArrayList<String> shoppingList = new ArrayList<>();

shoppingList这样的初始化应该放在构造函数中

itemValue应为专用最终

itemIndex可以在getIndex中转换为局部变量

getIndex这个名称表明它将返回索引,但它的无效,最好返回索引,并让方法的用户决定如何处理它。

最新更新