2014-11-27 2 views
0

약 80000 개 이상의 단어가 포함 된 텍스트 파일이 있습니다. 이 단어의 길이를 확인하고 배열 목록을 사용하지 않고 입력 한 번호와 일치하는지 확인하려고합니다. 다음부분 채워진 필드에 문자열 할당

part.array = new String[INITIAL_SIZE]; 

(그리고 :

PartArray part = new PartArray(); 

그리고 필드 : 나는 개체를 만들거야

public static int INITIAL_SIZE = 100; 
public static int size; 
public String[] array = new String[INITIAL_SIZE]; 

:

배열이 전역 변수를 가지고 말 모든 80000+ 단어를 포함 할 수있을 때까지 초기 크기에 2를 곱하여 다른 방법으로 배열을 확장합니다.

하지만 배열의 모든 단어를 0, 1, 2, ..... (80000 -1) 범위에 할당하려고합니다.

part.array[part.size++] = "aardvark"; 
..... 
part.array[part.size++] = "zymurgy"; 

이렇게 특정 길이의 단어를 인쇄 할 수 있습니다.

part.array[0]; 

하지만 어떻게해야합니까? 자바에서 다른 클래스를 생성해야합니까? 나는 그 텍스트 파일의 모든 단어 앞에 "String"을 넣고 싶지 않습니다.

먼저의가 무엇인가를 명확히하자 .. 난 당신이 뭘하려고했는지 이해하면

+0

왜 ArrayList를 사용하지 않으시겠습니까? – JimN

+0

@JimN 나는 ArrayList없이 이것이 가능하다는 것을 근본적으로 이해하려고 노력하고있다. – kris

+0

당신이 묘사하는 것은 ArrayList의 구현이라고 들었습니다. 따라서 내부적으로 배열을 사용하여 직접 구현하거나 기존 ArrayList를 사용할 수 있습니다. – JimN

답변

0

내가 totaly 잘 모르겠지만, 내가 이해에서, 당신은 ArrayList에 비슷한을 구현하고자합니다. 당신이 게시 코드 예제는 항상는, ArrayIndexOutOfBoundsException가 발생합니다 : 아무리 배열이 얼마나 큰

part.array[part.size++] = "aardvark"; 
..... 
part.array[part.size++] = "zymurgy"; 

, 그 배열의 외부 메모리에 액세스하려고합니다. 당신이 정말로 ArrayList에 (또는 다른 목록)을 사용하지 않으려면, 당신은 비슷한 방식으로 작동 자신의 클래스를 생성 할 수 있습니다 ..

public class StringList{ 
    public static final int DEFAULT_INITIAL_SIZE = 100; 
    public static final float DEFAULT_SCALE_FACTOR = 2; 

    private String[] content; 
    private float scaleFactor; 
    private int counter = 0; 

    public StringList(){ 
     this(DEFAULT_INITIAL_SIZE); 
    } 

    public StringList(int initialSize){ 
     this(initialSize, DEFAULT_SCALE_FACTOR); 
    } 

    public StringList(int initialSize, float scaleFactor){ 
     this.scaleFactor = scaleFactor; 
     content = new String[initialSize]; 
    } 

    public void add(String toAdd){ 
     //check if we ran out of space for new content.. 
     if(counter == content.length){ 
      //create a new array with twice the current arrays size 
      String[] temp = new String[(int) (content.length * scaleFactor)]; 
      //efficiently copy content from current array to temp 
      System.arraycopy(content, 0, temp, 0, content.length); 
      content = temp; 
     } 
     content[counter++] = toAdd; 
    } 

    public String get(int index){ 
     return content[index]; 
    } 

    public int size(){ 
     return counter; 
    } 
} 

그 클래스는 당신이 필요로하는 모든 일을해야한다 .. 여기에 간단한 예 ..

StringList stringList = new StringList(); 
stringList.add("aardvark"); 
// add more stuff... 
stringList.add("zymurgy"); 

for (int i = 0; i < stringList.size(); i++) { 
    String someText = stringList.get(i); 
    // do stuff with your string... 
} 
+0

ArrayList와 마찬가지로 generics를 사용하여 할 수 있지만, 원하는 것이 아니라고 생각합니다. 목록 또는 Iterable 인터페이스를 구현하면 좋을 것입니다.하지만 우리는 원하지 않습니다. 지저분 해지기 쉬운 것, 우리? :) –

관련 문제