简体   繁体   English

在Java中初始化后分配ArrayList

[英]Assigning a ArrayList after initializing it in Java

I am new to Java and I have a silly question. 我是Java新手,但我有一个愚蠢的问题。 Here's my pseudocode: 这是我的伪代码:

private static Map<String, ArrayList<byte[]> > myMap = new HashMap<String,ArrayList<byte[]> >();
public void setValue(String key, byte[] value) {
  ArrayList<byte[]> valueList = new ArrayList<byte[]>();
  if(this.myMap.containsKey(key))
  {      
       valueList = this.myMap.get(key);
  }
  valueList.add(value);
  this.myMap.put(key, valueList);
}

What I am trying to do is to check if the given key already has some value in the map. 我想做的是检查给定键在地图中是否已经有值。 If yes, it will retrieve the list of values and add the new value to this list. 如果是,它将检索值列表并将新值添加到此列表中。 If not, it will add a new key and list of value (with just one value) in the map. 如果没有,它将在地图中添加一个新的键和值列表(只有一个值)。

My question is about initializing the ArrayList with 'new' and then assigning it the value returned by this.myMap.get(key). 我的问题是关于使用'new'初始化ArrayList,然后为其分配this.myMap.get(key)返回的值。 Is it a good way to do it? 这是一个好方法吗? In C++ it will be an issue. 在C ++中,这将是一个问题。 I am not sure about Java. 我不确定Java。 What do you think? 你怎么看?

Your attempt is a reasonable way to achieve what you ask. 您的尝试是实现您的要求的一种合理方法。 The classic way of doing this, though, is to attempt to retrieve and then to populate it if no value was retrieved: 但是,执行此操作的经典方法是尝试检索,然后在未检索到任何值的情况下填充它:

Map<String, ArrayList<byte[]>> myMap = new HashMap<>();

public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.get(key);
    if (valueList == null) {
        valueList = new ArrayList<>();
        this.myMap.put(key, valueList);
    }
    valueList.add(value);
}

This saves one key lookup and one value insertion and consolidates the initialization logic to 4 consecutive lines. 这样可以节省一次键查找和一次值插入,并将初始化逻辑合并为4个连续的行。

If you are using Java 8, then you can do even better by using the Map#computeIfAbsent method. 如果您使用的是Java 8,则可以使用Map#computeIfAbsent方法Map#computeIfAbsent This is more efficient, more concise, and has the added advantage of maintaining concurrency constraints for map implementations that support concurrent operations: 这更高效,更简洁,并具有为支持并发操作的map实现维护并发约束的更多优点:

public void setValue(String key, byte[] value) {
    ArrayList<byte[]> valueList = this.myMap.computeIfAbsent(key, k -> new ArrayList<>());
    valueList.add(value);
}

Or even more concisely: 或更简而言之:

public void setValue(String key, byte[] value) {
    this.myMap.computeIfAbsent(key, k -> new ArrayList<>())
            .add(value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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