2014-10-13 3 views
1

ArrayList를 전달하고 max 요소를 반환 할 수있는 함수를 만들려고합니다. 전달되는 데이터 유형이 프리미티브가 아니기 때문에 정확한 해결책을 찾을 수 없었습니다. 또한 ArrayList를 ArrayList로 변환하지 않고 시도해 보았습니다. 여기에 내 (잘못된) 코드가 있습니다 :정수 배열의 Arraylist에서 최대 요소 찾기

public static void maxArrayListValue(ArrayList<int[]> arrayList) { 
    int maxArrayListValue = arrayList.get(0); // set first arrayList element as highest 

    for (int index=1; index < arrayList.size(); index++) { // cycle through each arrayList element 
     if (maxArrayListValue < arrayList.get(index)){  // if new element is > than old element 
     maxArrayListValue = arrayList.get(index);   // replace with new maxValue 
     maxArrayListIndex = index;       // record index of max element 
     } 
    } 
    return maxArrayListValue; 
} 

모든 입력은 감사하겠습니다.

답변

1

귀하의 방법은 아무것도 반환하지 않으며 각 배열의 값을 반복하고 싶습니다. 예 :

public static int maxArrayListValue(List<int[]> arrayList) { 
    int maxVal = Integer.MIN_VALUE; 
    for (int[] arr : arrayList) { 
     for (int v : arr) { 
      if (v > maxVal) { 
       maxVal = v; 
      } 
     } 
    } 
    return maxVal; 
} 
+0

이것은 완벽하게 작동했습니다. 나는 이것을 정확하게 이해하고 있는지 확인하고 싶다. arraylist의 각 배열을 통해 첫 번째 루프와 각 배열의 각 요소를 통해 두 번째 루프? –

+1

당신은'List '을 가지고 있으므로,'List <>'의'int []'내용을 먼저 반복 한 다음 그것을 가지고 있습니다! –

1

루프가 필요하지 않습니다. 그냥 java.util.Collections.max(arrayList)을 사용하십시오.

+0

이것이 작동하는지 잘 모르겠다. 원시 데이터 형식에서만 컬렉션을 사용할 수 있다고 생각 했는가? 오류가 발생합니다. "Collections 유형의 max () 메서드는 인수 (ArrayList )"에 적용 할 수 없습니다. " –

+0

콜렉션 요소가 자연 순서가없는 경우 두 번째 요소로 'Comparator'를 제공해야합니다. –