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