我有一个外部数据集,其中包含以下数据:userid,itemid,rating。我想将这些数据读入每个用户的userpreference对象。 userpreference对象包含userid,itemid数组和rating数组。我选择了一个阵列,因为性能需要尽可能快。我试图在没有物体的情况下进行操作,而是使用2D阵列。这有效,但我希望它是OOP并使用对象。我坚持把数据放到对象中。
数据集的一个例子是:
1,101,2.5
1,106,3.0
2,101,3.0
4,106,4.5
4,103,3.0
1,103,3.0
1,104,3.5
5,102,4.0
我的代码是什么样的
public class Main {
public static void main(String[] args) throws IOException{
//UserPreference bestaat uit userid, itemid[] en preferences[].
UserPreference [][] rating = new UserPreference[8][107];
int[][] userPref = new int[8][107]; //2d array test
BufferedReader br = new BufferedReader(new FileReader("userinfo.data"));
String line = null;
while ((line = br.readLine()) != null) {
String[] userratings = line.split(",");
int userColumn = Integer.parseInt(userratings[0]);
int itemColumn = Integer.parseInt(userratings[1]);
double ratingColumn = Double.parseDouble(userratings[2]);
System.out.println(userColumn + " " + itemColumn + " " + ratingColumn);
rating[userColumn][itemColumn] = ratingColumn;
userPref[userColumn][itemColumn] = (int) ratingColumn; //2d array test
}
br.close();
System.out.println("Rating: " + userPref[1][101]); // this works as an example, but not OO and reads out as an int instead of a double
System.out.println("Rating: " + rating[1][101]); //this does not work, because ratingcolumn is no object.
} }
ratingcolumn不会被识别为对象。我试着像之前使用过的2d数组那样做,但是效果不一样。我希望有人可以帮助我朝着正确的方向前进。
问候,
阿尔弗雷德
答案 0 :(得分:1)
OO解决方案可能是:
public static void main(final String[] args) throws IOException {
HashMap<Integer, User> users = new HashMap<Integer, User>();
BufferedReader br = new BufferedReader(new FileReader("userinfo.data"));
String line = null;
while ((line = br.readLine()) != null) {
String[] userratings = line.split(",");
int userColumn = Integer.parseInt(userratings[0]);
int itemColumn = Integer.parseInt(userratings[1]);
double ratingColumn = Double.parseDouble(userratings[2]);
User user = users.get(userColumn);
if (user == null) {
user = new User(userColumn);
users.put(userColumn, user);
}
user.add(new Item(itemColumn, ratingColumn));
}
br.close();
for (User user : users.values()) {
for (Item item : user.getItems()) {
System.out.println(user.getId() + "\t" + item.getId() + "\t" + item.getRating());
}
}
}
这两个班级:
public class User {
int id;
ArrayList<Item> items;
public User(final int id) {
this.id = id;
items = new ArrayList<Item>();
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public void add(final Item item) {
items.add(item);
}
public ArrayList<Item> getItems() {
return items;
}
}
public class Item {
int id;
double rating;
public Item(final int id, final double rating) {
this.id = id;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public double getRating() {
return rating;
}
public void setRating(final double rating) {
this.rating = rating;
}
}