2017-04-25 3 views
1

"선형 검색을 위해 다음과 같은 일반적인 방법을 구현해야합니다."하지만 일반적인 배열을 가질 수는 없습니다. 나의 급우들 중 누구도 그것을 이해할 수 없었고 우리 반 친구들을위한 TA도 없었습니다. 이것이 가능한가요, 그렇다면 올바른 방향으로 나를 가리킬 수 있습니까? 당신은 자바에서 일반 배열 생성 할 수 있습니다 감사합니다일반 선형 검색

public static void main(String[] args){ 
    Scanner scan = new Scanner(System.in); 
    String type = scan.next(); 
    int length = scan.nextInt(); 

    //checks the type and makes the appropriate array 
    if (type.equals("I")) { 
     int[] anArray = new int[length]; 
     for (int i = 0; i<length; i++) { 
      anArray[i] = scan.nextInt(); 
     } 
     int key = scan.nextInt(); 
     linearSearch(anArray, key); //Error, the method is not applicable for the arguments 
    } 
} 

public static <E extends Comparable<E>> int linearSearch(E[] list, E key) { 
    for (int i = 0; i<list.length; i++) { 
     if (list[i].equals(key)) { 
      return i; 
     } 
    } 
    return 0; 
} 

답변

2
  • .

  • 가장 확실하게 은 배열에 대한 일반적인 참조로 작동합니다.

  • 표시된 코드의 문제점은 원시 배열이 있고 제네릭이 참조에서만 작동한다는 것입니다. 당신이 Integer[] 대신 int[]를 사용하는 경우

프로그램이 작동합니다. 배열의

1

요소는 객체가 Comparable를 구현해야합니다, 그래서 당신은 정수 배열을 사용한다 :

Integer[] anArray = new Integer[length]; 
1
제네릭 프리미티브와 함께 작동 할 수 없습니다

, 당신은 래퍼 정수 클래스를 사용하는 nedd 것 때문에

Integer[] anArray = new Integer[length]; 
0

당신이 필요로하는 유형 ComparableanArray을하는 것입니다 java.lang.IntegerComparable 유형이 있습니다. 코드 :

package com.stackoverflow.json; 

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     String type = scan.next(); 
     int length = scan.nextInt(); 

     // checks the type and makes the appropriate array 
     if (type.equals("I")) { 
      Integer[] anArray = new Integer[length]; 
      for (int i = 0; i < length; i++) { 
       anArray[i] = scan.nextInt(); 
      } 
      int key = scan.nextInt(); 
      Comparable result = linearSearch(anArray, key); // Error, the method is not applicable 
             // for the arguments 
      System.out.println(result); 
     } 
    } 

    public static <E extends Comparable<E>> int linearSearch(E[] list, E key) { 
     for (int i = 0; i < list.length; i++) { 
      if (list[i].equals(key)) { 
       return i; 
      } 
     } 
     return 0; 
    } 

} 

인쇄 : result이 배열 요소의 검색 인덱스

I 
4 
12 
3 
4 
6 
3 
1 

하는 것으로 anArray