Is an Array of Arrays the right thing to do here?
My goal here is get an object that I can iterate over and grab my User's firstName and his favColor.
I have this:
for (Map user : userListing){
String firstName = (String) user.get(User.FIRST_NAME);
String favColor = (String) user.get(User.FAVORITE_COLOR);
// Build up some Arrayish object add "Bob", "red"
//
// what do i do here?
}
I'm unsure if I need to create, say an Array of Arrays?
My thought is that way I know the outer level of the Array is representative of each User, then once I'm the开发者_StackOverflow社区 next level deep, item[0]
would be the first name and item[1]
would be the color.
I'm not sure what would be the best solution here. Using a Map
to represent an user is already wrong in first place. I'd create a javabean class which represents an User
.
public class User {
private String firstName;
private String favoriteColor;
public String getFirstName() {
return firstName;
}
public String getFavoriteColor() {
return favoriteColor;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFavoriteColor(String favoriteColor) {
this.favoriteColor = favoriteColor;
}
// Add if necessary other javabean boilerplate like Serializable,
// default c'tor, full c'tor, equals(), hashCode(), toString().
}
Then just collect them in a List<User>
and pass that around instead.
Two ways to do it that are pretty simple
Map<String,Map<String,Double>> map2d = new HashMap<String,Map<String,Double>>(); For each new "x-coordinate", you'd have to instantiate a new sub-HashMap, and put it into map2d. This could all be wrapped in some new class. to retrieve an element, you just use: map2d.get(xKey).get(yKey)
Create a pair type and use that as your map key
http://www.velocityreviews.com/forums/t390520-2d-lookup-table.html
I would recommend:
create a java bean like object:
class Preferences{ //properties //getters //setters }
then have a array of Preferences
Preferences[] userPrefs = new Preferences[N]
iterate by
for (Preferences p : userPrefs) { //do the stuff}
精彩评论