Search code examples
javaarrayscustom-object

storing custom object with different primitive types in ArrayList


I want to create a custom object with three ints and a String and store that object in an arrayList, but I seem to be having issues with it and haven't been able to find documentation for exactly my issue online. I'm getting errors on the fac.add. here is the code

**made some changes to the code

package facility;
import dal.DataAccess;

public class FacilityInfo implements Facility {

private int buildingNo, roomNo, capacity;; 
private String type; //classroom, conference room, office, etc.

FacilityInfo(){}//default constructor

FacilityInfo(int b, int r, int c, String t){
    this.buildingNo = b; 
    this.roomNo = r; 
    this.capacity = c; 
    this.type = t; 
} 
package dal;
import java.util.*;

import facility.FacilityInfo;

public class DataAccess {
    List<FacilityInfo> fac = new ArrayList<FacilityInfo>();
    fac.add(new FacilityInfo (1,2,10,conference));//changed code here
}

Solution

  • That's because of two main reasons.

    First, 1,2,10,conference isn't a FacilityInfo object. You can't add the arguments of a FacilityInfo to the List, you have to add an actual object.

    Second, you can't have statements outside of a code block, and currently you are calling fac.add(...); directly in the class body.

    Try something like:

    public class DataAccess {
        List<FacilityInfo> fac = new ArrayList<FacilityInfo>();
    
        public void initializeFac() {
            fac.add(new FacilityInfo(1,2,10,"conference"));
            // etc.
        }
    }