【问题标题】:Tried to use Array List with Methods and Constructor. Can this be optimized?尝试将数组列表与方法和构造函数一起使用。这可以优化吗?
【发布时间】:2020-08-24 11:33:11
【问题描述】:

我已经在 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();
  }

}

【问题讨论】:

  • 这是一个更适合codereview.stackexchange.com 的问题。祝你好运!
  • 非常感谢您提供此链接,不知道该网站存在!我很感激!

标签: java arraylist methods constructor


【解决方案1】:

避免'//' cmets,依赖可读的代码和javadoc

java7之后

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

变成

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

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

itemValue 应该是 private final

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

getIndex 顾名思义,它会返回索引但它是无效的,最好返回索引并让方法的用户决定如何处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2018-06-30
    相关资源
    最近更新 更多