adding and retrieving objects from a list - java

My goal is to have a list of cars as an Object so that, I can retrieve a Car from that list. As well as get details of the cars. Can someone point me to the right direction
What I have done so far.
Create a class called Car and have the variables CarNum, carName, carPlate;
generated getters and setters for the variables and a toString as the carName
Create a class called CarCollection as follows
.
public class CarCollection {
private List<CarItem> mCarList;
public void addVan(CarItem v) {
mCarList.add(v);
}
public List<CarItem> getCarList() {
return mCarList;
}
The following test doesn't work. Why?
public class TestCarCollectionprocess {
public static void main(String[] args) {
CarItem car1 = new CarItem();
car1.setmCarName("Pedro");
car1.setmCarNum(1);
CarItem car2 = new CarItem();
car2.setmCarName("Rene");
car2.setmCarNum(2);
CarCollection carList = new CarCollection();
carList.addCar(car1);
carList.addCar(car2);
System.out.println(carList.getCarList());
}
}

What I see from your code, you should get NullPointerException in addVan method since you didn't initialize List, so change it like this:
private List<CarItem> mCarList = new ArrayList<>();

You are trying to add a CarItem to the CarCollection's mCarList without ever instantiating the list so you should be getting a null reference exception. In your carCollection class, create a constructor that sets
mCarList = new List<CarItem>();

Related

How do you add to an ArrayList using generics?

I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.

Assigning ArrayList object to Instance variable - java

The code snippet below is part of some code I am reading for an assignment but I cant understand the role of the copy variable in the snippet or what it does. I know its an instance of the Sample class, but why it is then assigned an ArrayList is not clear to me.
public class Sample implements Var{
private List lst1;
private List lst2;
public Sample() {
super();
}
public Sample(List lst1) {
this();
this.lst1 = lst1;
}
public List getLst1() {
return lst1;
}
public void setLst1(List lst1) {
this.lst1 = lst1;
}
#Override
public Var copy(){
Sample copy = new Sample(lst1);
copy.lst2 = new ArrayList(lst2);
return copy;
}
#Override
public void randomize(){
}
}
In fact the error message is explicit to show that you can't iterate over the variable copy because you haven't implemented the Iterable interface which allows you to do it. If you insist to loop over it and to have functions allowing you to do so: just visit this link Java Generics - Implementing the Iterable Interface where you can for exemple (if this is what you want) iterate over the elements of the two lists of an instance lst1 and lst2

How can I let my different objects in my ArrayList perform the method each class has (salaris())

Let's say you have different employees but each employee class has a salary() method. How can I make these different objects I made and put in an ArrayList use the method salary()?
public void betaalSalarissen(){
for(int counter = 0;werknemers.size()>counter;counter++){
Class objectClass = werknemers.get(counter).getClass();
**objectClass.salaris();** //this won't work, help please!
}
}
public void neemInDienst(Object persoon){ //objects from different classes, different employees
werknemers.add(persoon);
}
There's no reason to try to get the class; just use polymorphism.
public class Employee {
public double salaris() { ... }
}
public class CommissionedEmployee extends Employee {
#Override
public double salaris() { ... }
}
List<Employee> employees = new ArrayList<>();
// add some employees of whatever subtype(s)
for (Employee e : employees) {
e.salaris();
}
the quick solution here is to cast the result from werknemers.get(counter)``to yourEmployee` class (class name just guessed)
((Employee)werknemers.get(counter)).salaris();
but in the long run you should apply a generic parameter to the collection variable and the methods parameter:
private Collection<Employee> werknemers = new ArrayList<>();
public void neemInDienst(Employee persoon){ //objects from different classes, different employees
werknemers.add(persoon);
}
then you can simply iterate over the element without cast just as ChiefTwoPencils suggested.

java setter list object main not working

Hello I was wondering how to create an object in the list that is from another object.
For example I have a class Analysator and a class RoleGame.
There is no problem with the getters and setters.
But analysator1.setListRollenspellen(new RoleGame()); doesn't work.
Analysator class
public ArrayList<RoleGame> listRoleGame = new ArrayList<RoleGame>();
//getter
public ArrayList<RoleGame> getListRoleGame() {
return listRoleGame;
}
// setter
public void setListRoleGame(ArrayList<RoleGame> listRoleGame) {
this.listRoleGame = listRoleGame;
}
Main class
Analysator analysator1 = new Analysator();
analysator1.setListRoleGame(new RoleGame()); // <-- here
Your setter method expects ArrayList and you are passing RoleGame. If you want it to work, you could do something like:
public void setListRoleGame(RoleGame roleGame) {
this.listRoleGame.add(roleGame);
}
Analysator class expect the list as input, so provide a list to it:
Analysator analysator1 = new Analysator();
analysator1.setListRoleGame(Arrays.asList(new RoleGame())); // Should work

Add Object to array list. Get error when try add obect to ArrayList

Could somebody answer why there is a problem with my array list. I have a classes: List, People and Main (to run everything).
In List I am creating a new ArrayList to hold objects of type People.
In Main I am making new List object, then make new People object and then calling from List object add method, and at this point I get a nullPointerException exception.
public class Main {
public static void main(String[] args) {
List l = new List(); // making new List object
People p = new People(); // making new People object
l.addPeople(p); // calling from List object "addPeople" method and
}
// parsing People object "p"
}
import java.util.ArrayList;
public class List {
public List(){ //constructor
}
ArrayList<People>list; // new ArrayList to hold objects of type "People"
public void addPeople(People people){
list.add(people); // I get error here
}
}
public class People {
public People(){ // constructor
}
}
In the constructor:
list = new ArrayList<People>();
You did not instantiate the list at any time. In your constructor do this:
public List(){ //constructor
list = new ArrayList<People>();
}
I'm not sure if this is relevant, but it's a bad idea to name your class "List" since this will hide the List interface.
You need to put an ArrayList instance into your list field.

Categories

Resources