简体   繁体   中英

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 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

  1.  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) 
  2. Create a pair type and use that as your map key

http://www.velocityreviews.com/forums/t390520-2d-lookup-table.html

I would recommend:

  1. create a java bean like object:

    class Preferences{ //properties //getters //setters }

  2. then have a array of Preferences

    Preferences[] userPrefs = new Preferences[N]

  3. iterate by for (Preferences p : userPrefs) { //do the stuff}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM