2012-12-10 4 views
1

많은 코드가 있지만 여기에 맞는 비트가 있습니다.알 수없는 크기의 int 배열

나는 스텁으로 크기가 10 인 배열을 가지고 있는데, 어떤 크기의 배열을 얻을지 미리 알지 못한다. 단지 10보다 클 수 없다. 이론적으로 위의 코드에서

int[] arrTracker = new int[10]; 
    arrTracker = MyLibrary.SearchForABookISBN(true, AShelf, userParsedArr, aUserTitle); 

    for (int j = 0; j < 10; j++) 
    { 
     pln(AShelf[arrTracker[j]]); 

    } 

내가 그것을 통해 내 배열 I 루프를 가지고 있고 MyLibrary를 객체 배열에 내가 검색하고 책을 발견 한 경우 기본적으로 될 것입니다 내용을 (표시하면.

"userParsedArr는"사용자가 ISBN을 입력합니다. 여기

public int[] SearchForABookISBN (boolean aFlag, Book[] anArray, int[] AnISBN, String aTitle) 
{ 
    //This one was difficult. 

     int length = anArray.length; 
     int[] AnotherArr = new int[0]; 
     int[] AnotherArrTemp = new int[0]; 
     int[] AnotherArrNew = new int[0]; 

     boolean UFoundMe = false; 

     if (aFlag == true) 
     { 
      for (int i = 0; i < length; i++) 
      { 
       //Assume we find the ISBN 


       if ((anArray[i].Title.equals(aTitle))) 
       { 
        int counter = 0; 
        for (int j = 0; j < 9; j++) 
        { 
         if (anArray[i].ISBN[j] == AnISBN[j]) 
         { 
          counter++; 
         } 
         else 
         { 
          UFoundMe = false; 
          break; 
         } 
         if (counter == 9) 
         { 
          UFoundMe = true; 
         } 

        } 
        if (UFoundMe == true) 
        { 

         //Create our 'main' tracker at 1 + size of previous array. 
         AnotherArrNew = new int[1 + AnotherArr.length]; 
         if (AnotherArrTemp.length > 0) 
         { 
          //Copy values into a temp array. 
          //Make a new temp array 
          for (int m = 0; m < AnotherArr.length - 1; m++) 
          { 
           AnotherArrNew[m] = AnotherArrTemp[m]; 
          }  
         }   
         AnotherArrNew[(AnotherArrNew.length) - 1] = i; 

         AnotherArrTemp = new int[AnotherArrNew.length]; 
         for (int n = 0; n < AnotherArr.length; n++) 
         { 
          AnotherArrTemp[n] = AnotherArrNew[n]; 
         }       

         System.out.println(anArray[i]); 
        } 

       } 
      } 
     } 
     return AnotherArrNew; 
    } 
} 

기본 아이디어는 좀 빈 배열을 만들고, 내가 책을 발견하면 그때는 새로운 배열 한 사이즈 큰 만들고 기존의 배열을 던져이다, 임시 배열에 내용을 전송 한 다음주의 깊게 바를 만듭니다. 이전 어레이를 삭제하기 전에 내가 만든 것의 ckup을 사용하여 더 크게 만듭니다.

아마도 내가 10 권의 책을 가지고 있고, 3 권에는 동일한 제목과 ISBN이 있다고 할 수 있습니다. 나는 3 개의 배열을 반환 할 것으로 기대하지만, 미리 알지는 못한다. 왜냐하면 내가 20 권의 책이 주어지고 그것들 모두가 같기 때문이다.

내가 미리 가져 오는 배열의 크기를 알 수 있도록 MyLibrary.SearchForABookISBN (true, AShelf, userParsedArr, aUserTitle) .length가 작동합니까? 그러니 그냥 선언

int aLength = MyLibrary.SearchForABookISBN(true, AShelf, userParsedArr, aUserTitle).length 
int[] arrTracker = new int[aLength]; 
+1

미리 크기를 모르는 경우 ArrayList를 사용하십시오. 필요한 경우 배열로 변환 할 수 있습니다. – jlordo

답변

0

을 jlordo는 제안으로 : 단순히 ArrayList<Integer> 대신 int[]를 사용합니다. List<T> 인터페이스를 구현하므로 add(T element), remove(T Element), remove(int index) 및 아마도 contains(T element)과 같은 메소드가 있습니다.

ArrayList에 실제로 용량이 소진 된 후에는 크기가 조정됩니다 배열에 의해 백업됩니다,하지만 당신은 그것을 사용하는 그것에 대해 알 필요가 없습니다)

+0

내 프로필 사진 .... yikes! –

0

사용 빠른 자바 컬렉션의 힘 유지 보수가 가능한 코드. 당신의 Book에 ISBN을 추가

class Book { 
    private String isbn; 
    private String title; 
    public Book(int isbn, String title) { 
    this.isbn = isbn; 
    this.title = title; 
    } 
    @Override 
    public String toString() { 
    return "Book [isbn=" + isbn + ", title=" + title + "]"; 
    }  
} 

당신이 Map에 책을 당신 배열을 재구성 할 수 있다면, 당신은 일정한 시간에 제목을 기준으로 조회 할 수 있습니다. 이 new HashMap<>() 비트는 내가 생각했던 자바 7 코드

import static java.util.Arrays.asList; 

import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public static void main(String[] args) { 
    Map<String, List<Book>> library = new HashMap<>(); 
    library.put("a", asList(new Book("1", "a"), new Book("2", "a"))); 
    library.put("c", asList(new Book("3", "c"))); 
    System.out.println(search(library, "a")); 
} 

:

여기
private static List<Book> search(Map<String, List<Book>> library, String title) { 
    return library.get(title); 
} 

당신이 그것을 사용할 수있는 방법은 다음과 같습니다 추가 benifit으로, 코드는 배열 복사 없음 더 읽기 쉽고 유지 보수입니다 시도하는 것이 재미있을 수도 있습니다. 이전 버전의 경우 HashMap<String, List<Book>>을 사용하십시오.

+0

int ISBN을 9 자리로 사용하지 못했고, 오랜 작업을하지 못했고 BigInt를 구현하는 것도 문제가있었습니다. 그래서 배열로 바꿨습니다. – RaenirSalazar

+0

문자열로 트릭을해야합니다. – yakshaver

관련 문제