Cristian Cristian - 20 days ago 5
Java Question

How to set a list<Class> in a Class (Java)

I have the Pipe class:

public class Pipe {
private int length;

public Pipe(int length) {
this.length = length;
}
// plus getter and setter
}


Then the PipeGenerator class:

public class PipeGenerator {
private List<Pipe> pipeList;

public PipeGenerator(int numberOfPipes) {
List<Integer> availableTypes = generateAvailableTypes();
List<Pipe> pipes = createRandomPipesList(numberOfPipes, availableTypes);

this.pipeList.set(pipes);
// plus getter and setter
}
}


My code is highlighed with red in Intellij and I dont understand why. Here is a picture:

enter image description here

The createRandomPipesList method:

private List<Pipe> createRandomPipesList(int numberOfPipes, List<Integer> availableTypes) {
List<Pipe> pipes = new ArrayList<Pipe>();
addPipesToList(numberOfPipes, availableTypes, pipes);
return pipes;
}


So basically I want to generate a List and set it to the pipeList private property in the PipeGenerator class. What will be the way to do it?

Joe Joe
Answer

The set method of the List class is not doing what you think it is. Refer to the API http://docs.oracle.com/javase/8/docs/api/java/util/List.html#set-int-E-.

Instead just assign the new list.

pipeList = pipes;
Comments