-2

I'm trying to add different types of variables (String and Integer) to a object list, but when I'm running the code I always get a NullPointerException. I already debugged it and the variables aren't null. Can someone help me and tell me how I can add different types of variables to an object list?

private int x;
private int y;
private int z;
private int stockwerk;
private String address;
private List<Object> list;

public List<Object> getAttributeList () {

    list.add(1, this.x);
    list.add(2, this.y);
    list.add(3, this.z);
    list.add(4, this.stockwerk);
    list.add(5, this.address);

    return this.list;

}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Julian
  • 65
  • 2
  • 13
  • 1
    "I already debugged it and the variables aren't null" - you missed one. – user2357112 May 03 '16 at 15:56
  • 2
    It's also worth noting that you'll probably run into a null pointer error later since you insert your elements starting at index 1 instead of 0. So the first element in your list is always going to be null.... – Ethan May 03 '16 at 16:00

2 Answers2

4

You need to initialize the list once with list = new ArrayList<Object>() (for example). Otherwise list will be null and list.add will throw a NullPointerException.

Mark
  • 1,498
  • 1
  • 9
  • 13
0

Several errors in the code you posted;

1st: define a constructor where you can init the list

MyClass(){
    list = new ArrayList<Object>();
}

2nd: just because the list can take an object doesn't allow you to do this..

list.add(1, this.x);
    list.add(2, this.y);
    list.add(3, this.z);
    list.add(4, this.stockwerk);
    list.add(5, this.address);

you need to put in the list either an integer or a String

if you really need to do this: list.add(5, this.address); is because you are trying to specify the insertion order, but you are doing that in sequence, so it makes no much sense since the list could do that for you automatically

if you are instead trying to put some integer+ string in the list (I can infer this because of the title of the question) then re-desing the architecture and then define a map instead of a list, otherwise you will have a nice headache trying to read the data in the list....

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97