有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是数组的数组,在这里做正确的事情吗?

我的目标是得到一个我可以迭代的对象,并获取我用户的名字和他的favColor

我有这个:

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

我不确定是否需要创建,比如数组

我的想法是这样的,我知道数组的外层代表每个用户,然后一旦我进入下一层深度,item[0]将是第一个名字,item[1]将是颜色


共 (3) 个答案

  1. # 1 楼答案

    我不确定这里的最佳解决方案是什么。首先,使用Map来表示用户已经是错误的。我将创建一个javabean类,它表示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().
    }
    

    然后把它们收集到一个List<User>中,然后把它们传给别人

  2. # 2 楼答案

    有两种方法非常简单

    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. 创建一对类型并将其用作地图密钥

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

  3. # 3 楼答案

    我建议:

    1. 创建一个类似java bean的对象:

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

    2. 然后有一系列的偏好

      Preferences[] userPrefs = new Preferences[N]

    3. 通过for (Preferences p : userPrefs) { //do the stuff}