繁体   English   中英

如何通过在Java中将字符串作为引用传递给数组来返回数组?

[英]How do I return an array by passing a string as reference to the array in Java?

我有州名缩写定义的城市列表。

static List<String> AL = Arrays.asList("ABBEVILLE","ADAMSVILLE",.....
static List<String> AK = Arrays.asList("ADAK","AKHIOK",......

无论调用哪一个,数组都会发生同样的事情。 如何传递一个'AL'字符串并访问数组列表AL? 我目前使用的是一个案例陈述...但是它的所有50个代码都很多,我想把它修剪一下......

 case "AL":
   for(int index = 0; index < AL.size(); index++){.....}
 case "AK":
   for(int index = 0; index < AK.size(); index++){.....}

我喜欢这样的东西:

for(int index = 0; index < state_abbreviation.size(){
  System.out.println(state_abbreviation[index]);

您可以将每个List<String>存储在Map并使用州缩写作为地图的键。

import java.util.*;

class Test {
    public static void main(String[] args) {
        Map<String, List<String>> states = new HashMap<String, List<String>>();
        List<String> al = Arrays.asList("ABBEVILLE", "ADAMSVILLE", "...");
        List<String> ak = Arrays.asList("ADAK", "AKHIOK", "...");
        states.put("AL", al);
        states.put("AK", ak);
        System.out.println(states.get("AL").get(1)); // ADAMSVILLE
    }
}

暂无
暂无

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

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