2014-07-20 2 views
0

다음 ArrayList가 있습니다.루프를 사용하여 다른 이름을 가진 배열에 요소 추가

ArrayList<HashMap<Integer, Integer>> RP1 = new ArrayList<HashMap<Integer, Integer>>(); 
ArrayList<HashMap<Integer, Integer>> RP2 = new ArrayList<HashMap<Integer, Integer>(); 

루프의 각 ArrayList에 HashMap을 추가하고 싶습니다. 현재 다음과 같이 추가하고 있습니다 :

RP1.add(new HashMap<Integer, Integer>()); 
RP1.add(new HashMap<Integer, Integer>()); 
RP2.add(new HashMap<Integer, Integer>()); 
RP2.add(new HashMap<Integer, Integer>()); 

for 루프를 사용하는 방법이 있습니까? 현재의 방법은 비효율적 인 것처럼 보입니다.

+0

기다립니다 ** 왜 ** 당신은이 작업을 수행 할 수 있습니까? –

+0

비어있는 HashMap을 추가하면 비효율적입니다 –

답변

0

효율성과 관련하여 게시 한 풀어지지 않은 루프는 모든 루프 구성보다 빠릅니다. 간결함에 관심이 있고 둘 이상의 변수가있는 경우 별도의 변수가 아닌 ArrayListList<Map<Integer, Integer>>으로 선언하는 것이 좋습니다. 원하는 아직도 당신이 정말 이름으로 각 List<Map<Integer, Integer>>에 액세스해야하는 경우

List<List<Map<Integer, Integer>>> RPs = new ArrayList<>(); 

for (int i = 0; i < NUMBER_OF_ARRAYLISTS; i++) { 
    List<Map<Integer, Integer>> list = new ArrayList<>(); 
    for (int j = 0; j < NUMBER_OF_MAPS_PER_LIST; j++) { 
     list.add(new HashMap<Integer, Integer>()); 
    } 
    RPs.add(list); 
} 

:하지만, 나는 또한 당신 program to an interface이 (모든 인터페이스 유형과 같은 변수 [예를 들어, List]보다는 구현 유형 [ArrayList]를 선언)하는 것이 좋습니다 개별 변수를 제거한 다음 외부 구조를 Map<String, List<Map<Integer, Integer>>으로 선언하고 그 이름으로 요소를 추가합니다. 그러나 이것만으로는 프로그램을 작성하는 것이 더 효율적 일뿐만 아니라 (아마도) 더 쉽습니다.

+0

감사합니다. Ted, 나는 이것을 시도하고 다시 연락 할 것입니다. –

0

다음과 같이 시도해보십시오. 시험하지 않았어.

example(RP1,RP2); 
/* or example(RP1,RP1,RP2,RP2) */ 


public static void example(ArrayList<HashMap<Integer, Integer>> ... arrays){ 

     for (int i = 0; i < arrays.length; i++) 
      arrays[i].add(new HashMap<Integer, Integer>()); 
} 

대한 추가 정보 : https://today.java.net/article/2004/04/13/java-tech-using-variable-arguments

관련 문제