如何在主类中创建类x的对象同时在类x中向ArrayList添加值

时间:2019-01-03 22:33:38

标签: java arraylist

在主类中,我想同时创建一个ChainOfItems类的对象,同时还要填充Arraylist。我可以用空值填充它,但不能用数字填充它。

import java.util.*;

public class ChainOfItems {
    private ArrayList<Integer> itemes= new ArrayList<>();

    public Chain() {
    }

    public Chain(ArrayList<Integer> itemes) {
        super();
        this.itemes = itemes;
    }

    public ArrayList<Integer> getRequiredVNFTypes() {
        return itemes;
    }

    public void setitemes(ArrayList<Integer> itemes) {
        this.itemes = itemes;
    }   
}

public class main {
    public static void main(String[] args) {
        ChainOfItems item1=new ChainOfItems(null);///what i want to say the list contains two variable 1 and 10
    }
}

2 个答案:

答案 0 :(得分:0)

window.onload = function() {
  var el = document.getElementById('head-msg');
  el.innerHTML += 'Our payment processor is currently having an issue processing payments. Please come back to make your purchase. For additional assistance, contact Customer Service ';

  var a = document.createElement('a');
  var linkText = document.createTextNode('Contact Us');

  a.appendChild(linkText);
  a.href = '#';
  a.className = 'btn btn-sm btn-danger';

  el.appendChild(a);
}

上面应该为您工作。

使用接口代替给定的实现要好得多(请参阅OOP concepts)。考虑以这种方式更改类:

ArrayList<Integer> items= new ArrayList<>();
items.add(1);
items.add(10);
ChainOfItems item1=new ChainOfItems(items);

现在您可以提供public class ChainOfItems { private List<Integer> items; public Chain() { this(new ArrayList<>()); } public Chain(ArrayList<Integer> items) { this.items = items; } public List<Integer> getRequiredVNFTypes() { return items; } public void setItems(ArrayList<Integer> items) { this.items = items; } } 界面的许多实现:

List

ChainOfItems item1=new ChainOfItems(Arrays.asList(1,10));

答案 1 :(得分:0)

构造函数和setitemes(拼写)方法接受ArrayList。

item1.setitemes(new ArrayList(Arrays.asList(1, 10)));

或者:

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(10);
item.setitemes(list);