Reputation: 169
I have two classes, Room (belongs to one building) and Building (has n rooms). Building class has property "rooms" of type List and Room class has a property "building" of type Building. Both Room and Building are descendants of an abstract class.
Im creating new rooms from data from a csv file. Theres a "building_code" column for each room. I want to find a Building with corresponding value of property "code" (the property is declared in the abstract class) add it to rooms's "building" property and add room to Buldings's "rooms" List at the same time.
Since I want to use this functionality in class where I import the data, and another class that works with Buldings and Rooms (CRUD operations) should I create a method in Building class? With the following code I get an "incompatible types" exception on the line with For loop:
public Building findByCode(String code, List buildings) {
for (Building b : buildings) {
if (b.code.equals(code)) {
return b;
}
}
return null;
}
Upvotes: 0
Views: 126
Reputation: 1178
just as said in comments and answers you can solve your exception problem by declaring the type of List ( List ). but about the place of that function i agree with "Jason Armstrong" idea but you can also have "Utils" Class and declare this function as static method. then use it wherever you want.
public static Building findBuilding(String code, List<Building> buildings) {
for (Building b : buildings) {
if (b.code.equals(code)) {
return b;
}
}
return null;
}
Upvotes: 1
Reputation: 1260
You should define buildings as List<Building>
instead of just List
. That should fix your compilation error.
Building seems like a good place for this type of finder method if it's a business object. If it's a model/DTO, then put the logic elsewhere (service method/utility method). Model/DTOs should be thin, i.e. if Java had struct
.
Upvotes: 0