[英]What is a better way to initialize varibles in Java with less code?
在下面的示例中,什么是压缩我的代码的更好(最简单)的替代方法?
我在想可能有一种循环或排列这些的方法。 当我尝试将它们放入数组中时,语法错误出了。 也许arrayList或treeMap是更好的方法? 我对那些结构有些生疏。 我是否想深入了解?
private JMenuItem one = new JMenuItem("One");
private JMenuItem two = new JMenuItem("Two");
//... = ...;
//... = ...;
private JMenuItem sixtySeven = new JMenuItem("Sixty Seven");
for(conditions or array looping)
{
private JMenuItem i = new JMenuItem(i.toString().proper());//I have to research if there is even a "proper" method.
}
//Revised example below:
private JMenu edit = new JMenu("Edit");
private JMenu format = new JMenu("Format");
private JMenu view = new JMenu("View");
private JMenu help = new JMenu("Help");
private JMenuItem save = new JMenuItem("Save");
private JMenuItem open = new JMenuItem("Open");
private JMenuItem exit = new JMenuItem("Exit");
您不能在方法外部使用for
循环,如果将其移动到方法内部,则将声明局部变量,因此不允许使用private
。
而是使用数组 :
private JMenuItem[] menuItems = new JMenuItem[67];
{
// This code is in an initializer block and will
// run regardless of which constructor is called.
for (int i = 0; i < menuItems.length; i++) {
this.menuItems[i] = new JMenuItem(numberToWords(i + 1));
}
}
private static String numberToWords(int number) {
// Code here
}
您可以做的一件事就是将每个项目添加到一个arraylist中,而不用拥有67个变量来跟踪您,而只需要担心一个ArrayList。
使用Java 8以后,我将进行流传输和收集。 那应该节省很多行。
private static final int START = 1;
private static final int END = 67;
private List<JMenuItem> list;
private void initializeList(){
/*You will need the convertIntToSpelledString(int) method
*as @Andy Thomas mentioned above in his comment
*/
this.list = IntStream.rangeClosed(START, END).boxed()
.map(i -> new JMenuItem(convertIntToSpelledString(i))
.collect(Collectors.toList());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.